Description
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.
Analysis
典型的棧結構應用。
Code
class Solution {
public:
bool isValid(string s) {
stack<char> t;
for (char c : s){
if (c == '(' || c == '{' || c == '[')
t.push(c);
else
switch (c){
case ')':
if (!t.empty() && t.top() == '(')
t.pop();
else return false;
break;
case '}':
if (!t.empty() && t.top() == '{')
t.pop();
else return false;
break;
case ']':
if (!t.empty() && t.top() == '[')
t.pop();
else return false;
break;
default:
return false;
}
}
if (t.empty())
return true;
else return false;
}
};
Appendix
- Link: https://leetcode.com/problems/valid-parentheses/
- Run Time: 3ms