20. Valid Parentheses
题目地址:https://leetcode.com/problems/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.
今天看到一种解法,使用的stl,比我自己写的简单好多好多。
class Solution {
public:
bool isValid(string s) {
string left = "([{";
string right = ")]}";
stack<char> stk;
for(auto c:s){
if(left.find(c)!=string::npos){
stk.push(c);
}
else{
if(stk.empty()||stk.top()!=left[right.find(c)])
return false;
else
stk.pop();
}
}
return stk.empty();
}
};