Description
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.
Solution
使用堆栈,压栈时判断是否匹配,若匹配则弹出两个匹配者。这里匹配规则采用ASCII码的一个小trick,即’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ and ‘]’匹配者满足ASCII相差不大于2。
class Solution {
public:
bool isValid(string s) {
stack<char> bottle;
bottle.push(s[0]);
for(int i=1;i<s.size();i++){
if((!bottle.empty())&&(s[i]-bottle.top()<=2)&&(s[i]-bottle.top()>0))//若匹配则后者比前者ASCII码值大于0小于2。
{
bottle.pop();
}else{
bottle.push(s[i]);
}
}
return bottle.empty();
}
};