Given a string containing just the characters '(' and ')', find the length of the longest valid
(well-formed) parentheses substring.
For "(()", the longest valid parentheses substring is "()", which has length = 2.
Another example is ")()())", where the longest valid parentheses substring is "()()",
which has length = 4.
Solution: O(n).
1 class Solution { 2 public: 3 int longestValidParentheses(string s) { 4 stack<int> stk; 5 for(int i = 0; i < s.size(); i++) { 6 if(s[i] == '(') { 7 stk.push(i); 8 } 9 else if(!stk.empty()){ 10 s[stk.top()] = '*'; 11 s[i] = '*'; 12 stk.pop(); 13 } 14 } 15 16 int part = 0, res = 0; 17 for(int i = 0; i < s.size(); i++) { 18 if(s[i] == '*') { 19 part++; 20 } 21 else { 22 res = max(res, part); 23 part = 0; 24 } 25 } 26 res = max(res, part); 27 return res; 28 } 29 };