括号匹配算法
利用栈的LIFO的特点,我们可以进行左右括号的匹配,“()【】{}”
在右括号“)】}”左边最近的左括号必须是相对应的“(【{”,否则就不合法
每次匹配一对正确的括号,就要将其出栈,为外层的括号腾出空间。
#include <iostream>
#include <stack>
using namespace std;
bool isValid(string s) {
stack <char> sta;
char c,b;
int l=s.length();
for(int i=0;i<l;i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{')
{
sta.push(s[i]);
}
else if(s[i]==')')
{
if(sta.empty())
return false;
else if(c=sta.top(),c=='(')
sta.pop();
else
return false;
}
else if(s[i]==']')
{
if(sta.empty())
return false;
else if(c=sta.top(),c=='[')
sta.pop();
else
return false;
}
else if(s[i]=='}')
{
if(sta.empty())
return false;
else if(c=sta.top(),c=='{')
sta.pop();
else
return false;
}
}
if(sta.empty())
return true;
else
return false;
}
int main()
{
string s="()[]{}";
bool b=true;;
b=isValid(s);
if(b==true)
cout << "true";
else cout << "false";
return 0;
}