题目
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> st;
int size=s.size();
int i;
for(i=0;i<size;i++)
{
if(s[i]=='('||s[i]=='['||s[i]=='{')
st.push(s[i]);
else
{
if(!st.empty()&&
((st.top()=='('&&s[i]==')')||
(st.top()=='['&&s[i]==']')||
(st.top()=='{'&&s[i]=='}')))
st.pop();
else
return false;
}
}
if(i>=size&&st.empty())
return true;
else
return false;
}
};