Leetcode#20 Valid Parentheses
Published:
Link:
https://leetcode.com/problems/valid-parentheses/description/
Idea:
stack
Solution:
class Solution {
public:
bool isValid(string s) {
vector<char> vstack;
if (s.size() == 0)
return true;
for(int i=0; i<s.size(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
vstack.push_back(s[i]);
} else {
if(vstack.size()==0)
return false;
switch (s[i]) {
case ')':
if (vstack.back() != '(') {
return false;
} else {
vstack.pop_back();
}
break;
case ']':
if (vstack.back() != '[') {
return false;
} else {
vstack.pop_back();
}
break;
case '}':
if (vstack.back() != '{') {
return false;
} else {
vstack.pop_back();
}
break;
default:
return false;
}
}
}
if(vstack.size()>0)
return false;
return true;
}
};