Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
The brackets must close in the correct order, "()"
and "()[]{}"
are all valid but "(]"
and "([)]"
are not.
解释:
栈的简单应用,初始只接收'('、'['、'{'的输入。然后比较栈顶值与当前输入值是否匹配。
若匹配,栈顶元素出栈,否则当前元素进栈。
最后栈为空时表示字符串有效,否则无效。
代码
class Solution {
public:
bool match(char a,char b)
{
if(a == '(' && b == ')')
return true;
else if(a == '[' && b == ']')
return true;
else if(a == '{' && b == '}')
return true;
return false;
}
bool isValid(string s) {
if(s == "")
return false;
stack<char> sta;
if(s[0] != '(' && s[0] != '[' && s[0]!='{')
return false;
sta.push(s[0]);
int i = 1;
int num = 1;
for(i = 1;i<s.size();i++)
{
if(!sta.empty() )
{
if(match(sta.top(),s[i]))
{
sta.pop();
}
else
{
sta.push(s[i]);
}
}
else
{
sta.push(s[i]);
}
}
if(sta.empty())
return true;
else
return false;
}
};