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.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
解题思路:符号匹配,左括号和有括号匹配,不匹配就返回false。使用栈,左括号进栈,右括号进行判断是否出栈或者返回false。
注意:返回的是栈是否为空
class Solution {
public:;
bool isValid(string s) {
stack<char>l;
for(int i=0;i<s.size();i++){
switch(s[i]){
case '{':l.push(s[i]);
break;
case '[':l.push(s[i]);
break;
case '(':l.push(s[i]);
break;
case '}':if(l.empty()||l.top()!='{')return false;else l.pop();break;
case ']':if(l.empty()||l.top()!='[')return false;else l.pop();break;
case ')':if(l.empty()||l.top()!='(')return false;else l.pop();break;
default:;
}
}
return l.empty();
}
};