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.
括号配对问题,用栈来解决是最方便简单的,将“(”“[”“{”这些左括号推入栈中,再用栈顶的括号与右括号对比,如果匹配就将左括号pop出栈,如果不匹配就返回false。
class Solution {
public:
bool isValid(string s) {
stack<char> paren;
for (int i = 0; i < s.length(); i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') paren.push(s[i]);
if (s[i] == ')') {
if (paren.empty() || paren.top() != '(') return false;
else paren.pop();
}
if (s[i] == ']') {
if (paren.empty() || paren.top() != '[') return false;
else paren.pop();
}
if (s[i] == '}') {
if (paren.empty() || paren.top() != '{') return false;
else paren.pop();
}
}
return paren.empty();
}
};