class Solution { public: int longestValidParentheses(string s) { int n=s.size(); int cnt = 0; int max = 0; vector<int> st; string strip(n, ' '); int i = 0; for (auto c:s) { if (c == '(') { st.push_back(i); } else { if(!st.empty()) { auto left = st.back(); st.pop_back(); strip[i] = ')'; strip[left] = '('; } } i++; } for (auto c:strip) { if (c != ' ') { cnt++; } else { max = max<cnt ? cnt : max; cnt = 0; } } if (cnt) max = max<cnt ? cnt : max; return max; } }; 就输出所有合法的括号匹配,用同样长度字符串来存放,不合法位置默认用空格, 这样从前往后找最长的一串就是最大长度