Posted onEdited onInLeetCodeDisqus: Symbols count in article: 1.2kReading time ≈1 mins.
stack O(n) time O(n) space
1 2 3 4 5 6 7 8 9 10 11 12 13 14
d = {')': '(', '}': '{', ']': '['}
classSolution: defisValid(self, s: str) -> bool: stk = [] for c in s: if c in d: ifnot stk or d[c] != stk[-1]: returnFalse else: stk.pop() else: stk += c # 注意这里c是一个字符所以可以用+= returnnot stk
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
unordered_map<char, char> m = {{')', '('}, {'}', '{'}, {']', '['}}; classSolution { public: boolisValid(string s){ string stk; for (char c : s) { if (m.count(c)) { if (!stk.empty() && stk.back() == m[c]) { stk.pop_back(); } elsereturnfalse; } else { stk += c; } } return stk.empty(); } };