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
栈+哈希
class Solution {
public:
stack<char> s1;
stack<char> s2;
unordered_set<char> set1{'(','[','{'};
unordered_map<char, char> map1{{')','('},{']','['},{'}','{'}};
bool isValid(string s) {
if (s.size() % 2) return false;
for (auto c : s) {
if (set1.count(c)) {
s1.push(c);
}
else {
if (s1.size() && s1.top() == map1[c]) {
s1.pop();
}
else s2.push(c);
}
}
return s1.empty() && s2.empty();
}
};