stack解决括号匹配问题

#include<iostream>
#include<string>
#include<stack>
using namespace std;
bool judge(const string& str)
{
	stack<char> s;
	for (auto i : str)
	{
		switch (i)
		{
		case '(':	s.push(i);	break;
		case '[':	s.push(i);	break;
		case '{':	s.push(i);	break;
		case ')':
			if (!s.empty() && s.top() == '(')   //使用top前需判断stack是否为空
			{
				s.pop();	break;
			}
			else
				return false;
		case ']':
			if (!s.empty() && s.top() == '[')
			{
				s.pop();	break;
			}
			else
				return false;
		case '}':
			if (!s.empty() && s.top() == '{')
			{
				s.pop();	break;
			}
			else
				return false;
		default:
			break;
		}
	}
	return s.empty();
}
int main()
{
	string str;
	while (cin >> str)
		cout << (judge(str) ? "yes" : "no") << endl;   //注意:条件表达式优先级低,需加括号
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_44009743/article/details/89049259
今日推荐