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.
算法流程为:
1、从前向后扫描字符串;
2、遇到左括号x,就压栈x;
3、遇到右括号y:
如果发现栈顶元x和该括号y匹配,则栈顶元素出栈,继续判断下一个字符;
如果栈顶元素x和该括号y不匹配,字符串不匹配;
如果栈为空,字符串不匹配;
4、扫描完成后,如果栈恰好为空,则字符串匹配,否则,字符串不匹配。
解法1:
class Solution {
public:
bool isValid(string s) {
stack<char> stk;
for(int i=0;i<s.size();i++)
{
char c=s[i];
if(c=='('||c=='{'||c=='[')
stk.push(c);
else{
if(stk.size()==0)
return false;
char pre=stk.top();
switch(c)
{
case ')':
if(pre=='(')
stk.pop();
else
return false;
break;
case ']':
if(pre=='[')
stk.pop();
else
return false;
break;
case '}':
if(pre=='{')
stk.pop();
else
return false;
break;
}
}
}
if(stk.empty())
return true;
else
return false;
}
};
解法2:
class Solution {
public:
bool isValid(string s) {
string left="([{";
string right=")]}";
stack<char> stk;
for(auto c:s)
{
if(left.find(c)!=string::npos)
stk.push(c);
else{
if(stk.empty()||stk.top()!=left[right.find(c)])
return false;
else
stk.pop();
}
}
if(stk.empty())
return true;
else
return false;
}
};