Valid Parentheses
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.class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<char> v;
for(int ii = 0; ii < s.length(); ++ii){
switch(s[ii]){
case '{':
case '[':
case '(':
v.push(s[ii]);
break;
case '}':
case ']':
case ')':
if (v.empty()) return false;
char c = v.top();//expect {[(
if (c+1 == s[ii] || c+2 == s[ii]) v.pop();//ASCII
else return false;
}
}
return v.empty();
}
};
No comments:
Post a Comment