Valid Parentheses
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.
解题思路:
一个简单的字符匹配问题,安装题目的要求很快可以写出程序。
Code:
class Solution {
public:
bool isValid(string s) {
stack<char> st;
for(int i=0;i<s.size();i++)
{
if(s[i]==')' || s[i]==']' || s[i]=='}')
{
if(st.empty())
return false;
else
{
char ch=st.top();
st.pop();
if((ch=='('&&s[i]!=')') ||(ch=='[' && s[i]!=']') || (ch=='{' && s[i]!='}'))
return false;
}
}
else
st.push(s[i]);
}
return st.empty();
}
};