简单题。使用stack就行了。不过一开始忘了判断'['和']'的情况。要判断stack是否为空。
#include <string> #include <stack> using namespace std; class Solution { public: bool isValid(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function stack<char> st; for (int i = 0; i < s.size(); i++) { if (s[i] == '(' || s[i] == '[' || s[i] == '{') { st.push(s[i]); } else if (s[i] == ')' || s[i] == ']' || s[i] == '}') { if (st.empty()) return false; char c = st.top(); st.pop(); if (c == '(' && s[i] != ')') return false; if (c == '[' && s[i] != ']') return false; if (c == '{' && s[i] != '}') return false; } } if (!st.empty()) return false; return true; } };
python3
class Solution: def isValid(self, s: str) -> bool: stack = [] mapping = {'(': ')', '{': '}', '[': ']'} for c in s: if len(stack) == 0: stack.append(c) else: p = stack.pop() if p in mapping and c == mapping[p]: continue else: stack.append(p) stack.append(c) return len(stack) == 0