Problem : Valid Parentheses
Question
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) {
stack<char> p;
for(int i = 0; i < s.size(); i++) {
if(s[i] == '(' || s[i] == '{' || s[i] == '[') {
p.push(s[i]);
}
else {
if (s[i] == ')') {
if (p.size() != 0 && p.top() == '(')
p.pop();
else return false;
}
if (s[i] == ']') {
if (p.size() != 0 && p.top() == '[')
p.pop();
else return false;
}
if (s[i] == '}') {
if (p.size() != 0 && p.top() == '{')
p.pop();
else return false;
}
}
}
if (p.size() != 0)
return false;
return true;
}
};