题目
给定一个字符串只包含(,),{,},[和],判断输入是否合法。括号必须按照正确顺序排列,如()和()[]是合法的,而(]和([)]不合法。
输入
()[]
输出
True
输入
([)]
输出
False
分析
利用栈stack的特性。
代码
#include <iostream>
#include <string>
#include <stack>
using namespace std;
int main()
{
string str;
cin >> str;
string left = "([{";
string right = ")]}";
stack<char> stk;
for (auto c : str)
{
if (left.find(c) != string::npos)
{
stk.push (c);
}
else
{
if (stk.empty () || stk.top () != left[right.find (c)])
{
cout << "False" << endl;
return 0;
}
else
{
stk.pop ();
}
}
}
if (stk.empty())
{
cout << "True" << endl;
}
return 0;
}