最长有效括号
先用栈判断括号匹配,在把所有匹配的括号标记为0,然后求最长的0序列
class Solution { public: int longestValidParentheses(string s) { int len = s.length(); int ans = 0; stack<int>p; for (int i = 0; i < len; i++) { if (s[i] == '(') { p.push(i); } if (s[i] == ')' && !p.empty()) { s[i] = '0'; s[p.top()] = '0'; p.pop(); } } int temp = 0; for (int i = 0; i < len; i++) { if (s[i] == '0') { temp++; } else { ans = max(ans, temp); temp = 0; } } ans = max(ans, temp); return ans; } };
等风起的那一天,我已准备好一切