给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。 注意空字符串可被认为是有效字符串。
我还是很喜欢用栈的。
符号匹配问题很容易就会想到入栈出栈操作吧。
bool isValid(string s) {
stack<char> strStack;
int i=0;
while(i<s.size())
{
//cout<<s[i];
if(!strStack.empty())
{
if((strStack.top()=='('&&s[i]==')')||(strStack.top()=='['&&s[i]==']')||(strStack.top()=='{'&&s[i]=='}'))
{
strStack.pop();
}
else
{
//cout<<" pushed"<<endl;
strStack.push(s[i]);
}
}
else
{
//cout<<" pushed"<<endl;
strStack.push(s[i]);
}
i++;
}
return strStack.empty();
}