20. Valid Parentheses
Total Accepted: 102983
Total Submissions: 352605
Difficulty: Easy
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.
Subscribe to see which companies asked this question
Have you met this question in a real interview?
验证字符串括号是否配对合法。
经典问题了
用个栈就解决。
class Solution {
public:
bool isValid(string s)
{
int len=s.length();
if(len%2)
return false;
stack<char> st;
for(int i=0;i<len;i++)
{
if(!st.empty())
{
if ((st.top()=='['&&s[i]==']')||(st.top()=='('&&s[i]==')')||(st.top()=='{'&&s[i]=='}'))
st.pop();
else
st.push(s[i]);
}
else
{
st.push(s[i]);
}
}
return st.empty();
}
};