【LeetCode】20. 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) { if (s.size() == 0) return true; stack<char> bracket_stack; int i = 0; while (i < s.size()) { if (s[i] == '(' || s[i] == '{' || s[i] == '[') { bracket_stack.push(s[i++]); }else { if (!bracket_stack.empty() && (s[i] == ')' && bracket_stack.top() == '(' || s[i] == '}' && bracket_stack.top() == '{' || s[i] == ']' && bracket_stack.top() == '[')) { bracket_stack.pop(); ++i; } else { return false; } } } if (!bracket_stack.empty()) return false; return true; } };


浙公网安备 33010602011771号