[LeetCode] Valid Parentheses

20. Valid Parentheses

Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  • Time : O(n)
  • Space : O(1) (constant)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> pairs {{')','('}, {']','['}, {'}','{'}};
vector<char> st;
for(int i = 0; i < s.length() and i <= s.length() - st.size(); i++) {
if(s[i] == '(' or s[i] == '[' or s[i] == '{') st.push_back(s[i]);
else {
if (st.empty() || st.back() != pairs[st[i]]) return false;
st.pop_back();
}
}

return st.empty();
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/valid-parentheses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.