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.
典型的用stack解决的问题。
solution:
bool isValid(string s) { if (s.empty() || s.size() % 2 != 0) return false; stack<char> stk; for (int i = 0;i < s.size();++i) { if(s[i] == '(' || s[i] == '[' || s[i] == '{') stk.push(s[i]); else { if (stk.empty()) return false; char ch = stk.top(); stk.pop(); if(s[i] == ')' && ch != '(') return false; if (s[i] == ']' && ch != '[') return false; if (s[i] == '}' && ch != '{') return false; } } return stk.empty(); }
如有其它解法,欢迎来稿。