首页 > 代码库 > LeetCode[stack]: Valid Parentheses

LeetCode[stack]: 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.

典型的栈的应用,直接附上代码:

C++ code
bool isValid(string s) { stack<char> parentheses; for (auto c : s) { if (c == ‘(‘ || c == ‘{‘ || c == ‘[‘) parentheses.push(c); else { if (parentheses.empty()) return false; else if (c == ‘)‘ && parentheses.top() != ‘(‘) return false; else if (c == ‘]‘ && parentheses.top() != ‘[‘) return false; else if (c == ‘}‘ && parentheses.top() != ‘{‘) return false; parentheses.pop(); } } return parentheses.empty(); }

LeetCode[stack]: Valid Parentheses