【20】Valid Parentheses (2018年11月28日,复习, ko)
给了一个字符串判断是不是合法的括号配对。
题解:直接stack
1 class Solution { 2 public: 3 bool isValid(string s) { 4 set<char> st{'(', '[', '{'}; 5 map<char, char> mp{{'(', ')'}, {'{', '}'}, {'[', ']'}}; 6 stack<char> stk; 7 for (auto c : s) { 8 if (st.find(c) != st.end()) { 9 stk.push(c); 10 } else { 11 if (stk.empty()) { return false; } 12 char t = stk.top(); 13 if (mp[t] == c) { 14 stk.pop(); 15 } else { 16 return false; 17 } 18 } 19 } 20 return stk.empty(); 21 } 22 };