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 isValid(string s) {
stack<char> sta;
for(int i=0;i<s.length();i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{') sta.push(s[i]);
else if(s[i]==')')
{
if(!sta.empty()&&sta.top()=='(') sta.pop();
else return false;
}
else if(s[i]=='}')
{
if(!sta.empty()&&sta.top()=='{') sta.pop();
else return false;
}
else if(s[i]==']')
{
if(!sta.empty()&&sta.top()=='[') sta.pop();
else return false;
}
}
if(!sta.empty()) return false;
return true;
}
};