数据结构栈的应用------括号匹配问题

1.思路

括号匹配问题,首先有一个待匹配的字符串(一串括号)和一个栈(后进先出),一直判断是否有待匹配括号(有左压入栈,有右就匹配):
一:有。判断栈是否为空
(一)空。匹配失败。
(二)非空。
---------判断待匹配括号左右
---------左:压入栈;
---------右:与栈内括号进行匹配(成功true失败false)。
二:没有。判断栈是否为空(一)空。匹配成功。(二)非空。匹配失败。

2.代码实现

#include<cstdio>
#include<stack>
using namespace std;

bool Bracket_check ( char str[], int length ){//传入待匹配括号和其个数
	stack < char > st;//STL标准模板库
	for ( int i = 0; i < length; i++ ){//for循环实现判断是否还有待匹配括号
		if ( str[i] == '(' || str[i] == '[' || str[i] == '}' )
			st.push ( str[i] );//有且为左括号压入栈
		else{
			if ( st.empty() )//没有,判断栈空否
				return false;
			char topelem = st.top();//注意st.pop不返回值
			st.pop();//需要返回值要和top连用
			if ( str[i] == ')' && topelem != '(')
				return false;
			if ( str[i] == ']' && topelem != '[')
				return false;
			if ( str[i] == '}' && topelem != '{')
				return false;
		}
	}
	return st.empty();//最后无待匹配且栈也为空,即匹配成功
}
int main()
{
	char str[11] = "()(())";//字符串最后位置有'\0'
	printf("%s\n\n",str);
	if ( Bracket_check ( str, 6 ) )
	//注意传入参数一定是待匹配括号个数,不能多不能少
		printf( "匹配成功!");
	else 
		printf ( "匹配失败!"); 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值