classSolution { public: boolisValid(string s){ unordered_map<char, int>m{{'(',1},{'[',2},{'{',3}, {')',4},{']',5},{'}',6}}; stack<int> st; for(char c : s){ int index = m[c]; if(index >= 1 && index <= 3){ st.push(c); } elseif(!st.empty() && m[st.top()] == index-3){ st.pop(); } else{ returnfalse; }
} return st.empty(); } };
1 2 3 4 5 6 7 8 9 10 11
classSolution: defisValid(self, s: str) -> bool: dic = {')':'(',']':'[','}':'{'} stack = [] for i in s: if stack and i in dic: if stack[-1] == dic[i]: stack.pop() else: returnFalse else: stack.append(i) returnnot stack