题目:有效括号
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
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
如果字符是open则入栈,如果是close,则通过hashmap比较是否与栈顶括号成对,如果不成对,直接返回错误,如果成对,则栈顶元素出栈,继续下一个字符
class Solution {
public:unordered_map<char,char> map = {{ ')','('},{ ']','['},{ '}','{'}};bool isValid(string s) {if(s == "") return true;stack<char> stk;for(int i = 0; i < s.length();i++){if(s[i] == '(' || s[i] == '[' || s[i] == '{'){stk.push(s[i]);}else if(s[i] == ')' || s[i] == ']' || s[i] == '}'){char tmp = map[s[i]];if(!stk.empty() && tmp == stk.top()){stk.pop();}elsereturn false;}elsereturn false;}if(stk.empty()) return true;return false; }
};