C++算法之括号匹配问题

bool judge(const string& temp, stack<char>& test)
{
	int i =0;
	char stack_pop_char;
	while(i < temp.size()  )
	{
		//遍历字符串,左括号和其他字符入栈,其他类型字符出栈
		if(temp[i] =='(' || temp[i] == '[' || temp[i] == '{')
		{
			test.push(temp[i]);
		}
		if(temp[i] == ')' || temp[i] == ']' || temp[i] == '}')
		{
			if(test.size() > 0)	//需要判断栈是否非空,为空则不能进行出栈,直接返回False 
			{
				stack_pop_char = test.top();
				test.pop();
				switch(temp[i]) 
				{
					case ')':
						if (stack_pop_char == '('){
							continue;
						}
						else return  false;
						
						case ']':
						if (stack_pop_char == '['){
							continue;
						}
						else return  false;
						
						case '}':
						if (stack_pop_char == '{'){
							continue;
						}
						else return false;
				}
			}
			else return false;
			
		}
		++i;
	} 
	return true;
}

括号匹配问题利用了从左往右遍历字符串时,栈顶的左括号离当前位置最近的特性完成工作。栈还有一个更为出名的应用表达式的求值

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值