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.
LeetCode上的原题,请参见我之前的博客Valid Parentheses。
class Solution { public: /** * @param s A string * @return whether the string is a valid parentheses */ bool isValidParentheses(string& s) { stack<char> st; for (char c : s) { if (c == ')' || c == '}' || c == ']') { if (st.empty()) return false; if (c == ')' && st.top() != '(') return false; if (c == '}' && st.top() != '{') return false; if (c == ']' && st.top() != '[') return false; st.pop(); } else { st.push(c); } } return st.empty(); } };
本文转自博客园Grandyang的博客,原文链接:验证括号[LintCode] Valid Parentheses ,如需转载请自行联系原博主。