Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
这题的重点在于括号要合乎规范,包括一一对应,顺序也要按照{[(来排列。c++的栈用起来就很合适了,因为它的先进后出特性。
class Solution {
public:
bool isValid(string s) {
stack<char> res;
//利用栈的特性,先进后出,所以一遇到左边的就先压入。然后遇到右边的,就到顶出栈顶元素,这样也符合{[()]}的排列顺序
for(int i=0;i<s.size();i++){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
res.push(s[i]);
}
else{
if(res.empty()) return false;
char top=res.top();
res.pop();
char relative;
if(top == '(') relative=')';
else if(top == '{') relative='}';
else if(top == '[') relative=']';
if(s[i] != relative) return false;
}
}
if(!res.empty()) return false;
return true;
}
};