Leetcode.32. Longest Valid Parentheses
题意:求最长可配对括号子串
题解:遍历s,'('则入栈,‘)’则配对栈顶,若成对,则标记,否则也入栈(或清空栈),遍历完后,遍历一遍标记数组,找最长
1 class Solution { 2 public: 3 int longestValidParentheses(string s) { 4 stack<int> st; 5 vector<bool> ispair(s.size()); 6 for (auto i = 0; i < s.size(); i++) { 7 if (s[i] == '(') { 8 st.push(i); 9 } 10 else if (s[i] == ')' && !st.empty() && s[st.top()] == '(') { 11 ispair[st.top()] = true; 12 ispair[i] = true; 13 st.pop(); 14 } 15 else { 16 st.push(i); 17 } 18 } 19 int p = 0, cnt = 0, mx = 0; 20 while (p < s.size()) { 21 cnt = 0; 22 while (p < s.size() && ispair[p]) { 23 cnt++; 24 p++; 25 } 26 if (mx < cnt) 27 mx = cnt; 28 p++; 29 } 30 return mx; 31 } 32 };