题目描述
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
解题思路
这道题在学栈的时候有学到,连续压入栈中,如果接下来要入栈的和栈顶的相匹配,则弹出,否则压入。
class Solution {
private:
map<char,char> parenthe={{'}','{'},{')','('},{']','['}};
public:
bool isValid(string s) {
stack<char> parentheses;
for(int i=0;i<s.size();i++)
{
if(parentheses.empty()||parentheses.top()!=parenthe[s[i]])
parentheses.push(s[i]);
else
parentheses.pop();
}
return parentheses.empty();
}
};