LeetCode : Valid Parentheses
问题:
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) {
unordered_map<char,int> m;
vector<int> v;
m['('] = 1;
m[')'] = -1;
m['{'] = 2;
m['{'] = -2;
m['{'] = 3;
m['{'] = -3;
for(int i=0;i<s.length();i++){
if(m[s[i]]>0){
v.push_back(m[s[i]]);
}else if(!v.empty() &&( m[s[i]] + v[v.size()-1] )== 0){
v.pop_back();
}else{
return false;
}
}
if(v.empty()){
return true;
}else {
return false;
}
}
};