题目链接: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.
class Solution {
public:
bool isValid(string s)
{
unordered_map<char, char> map;
map['(']=')';
map['{']='}';
map['[']=']';
stack<char> charStack;
for(int i=0;i<s.length();i++)
{
if(map.find(s[i])!=map.end())
charStack.push(s[i]);
else
{
if(!charStack.empty()&&map[charStack.top()]==s[i])
charStack.pop();
else
return false;
}
}
return charStack.empty();
}
};