EASY
Valid Parentheses
Given a string s 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.
- Every close bracket has a corresponding open bracket of the same type.
Example
Input:
s = "()[]{}"
Output:
true
Explanation:
All brackets are closed in the correct order.
Constraints
- 1 ≤ s.length ≤ 10⁴
- s consists of parentheses only '()[]{}'
Solution: Stack
- Time Complexity: O(n)
- Space Complexity: O(n)
C++
class Solution {
public:
bool isValid(string s) {
string temp;
unordered_map<char, char> m = {{')', '('}, {']', '['}, {'}', '{'},};
for (auto c : s) {
if (!m.count(c)) temp+= c;
else {
if (temp.empty() || temp.back() != m[c]) return false;
temp.pop_back();
}
}
return temp.size() == 0;
}
};