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.
题意
判断所给字符串是否符合规则,即括号的配对。
题解
用栈的特性可以很方便解决这个问题,遍历到左边的括号则入栈,遍历到右边的则把栈顶的元素拿来对比,然后再出栈。
左右匹配有两个方法 一个是用"([{" 与")]}",左边括号的下标与右边括号的下标一样 即stk.top () == left[right.find (c)]来判断
还有一个办法是用ascii码 注意其中两个左括号+1为其右括号 但有一个的左括号+2才是其右括号。这个做法可能会有点不严谨,但在输入保证是只有括号的情况下还是没问题的。
class Solution {
public:
bool isValid(string s) {
stack<char> left;
for(int i=0;i!=s.size();i++)
{
if(s[i]==')'||s[i]==']'||s[i]=='}')
{
if(left.empty())
return false;
else if(s[i]!=left.top()+1&&s[i]!=left.top()+2)
return false;
else left.pop();
}
else left.push(s[i]);
}
if(left.empty())
return true;
return false;
}
};