Difficulty: Easy
Back to another easy problem yippe. Classic problem here, we want to use a stack to keep track of the currently open parentheses.
If we find a open parentheses, we can append it to the stack. If we find a closed parentheses, there are 3 options:
class Solution {
public:
bool isValid(string s) {
vector<char> stack {};
unordered_map<char, char> matching {
{'}', '{'},
{']', '['},
{')', '('}
};
for (char c: s) {
if (!matching.contains(c)) {
// open
stack.push_back(c);
} else {
// closed
if (stack.empty() || stack.back() != matching[c]) {
return false;
}
stack.pop_back();
}
}
return stack.empty();
}
};
Time Complexity:
O(n)Space Complexity:
O(n)Time Taken:
7m 7s