Longest Valid Parentheses
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.
思路:
我第一反应是想到了栈(不像好多网友第一下想到DP, DP基础还是不够扎实。。。),但是没想到栈里存的是index。后来发现如果发生失配,那么就更新last,表示上一组匹配的括号的结束地址是什么,否则的话就用当前index减去栈顶的index。
代码:
1 int max(int a, int b){ 2 if(a > b) 3 return a; 4 return b; 5 } 6 int longestValidParentheses(string s) { 7 // IMPORTANT: Please reset any member data you declared, as 8 // the same Solution instance will be reused for each test case. 9 int l = s.length(); 10 if(l < 2) 11 return 0; 12 int i; 13 stack<int> Stack; 14 int result = 0; 15 int last = -1; 16 for(i = 0; i < l; i++){ 17 if(s[i] == '('){ 18 Stack.push(i); 19 } 20 else{ 21 if(Stack.empty()){ 22 last = i; 23 } 24 else{ 25 Stack.pop(); 26 if(Stack.empty()){ 27 result = max(result, i-last); 28 } 29 else{ 30 result = max(result, i-Stack.top()); 31 } 32 } 33 } 34 } 35 return result; 36 }