32. 最长有效括号-LetCde
一,运用栈的方法 二,动态规划:待更新
解题思路:
1.需有一个变量start记录有效括号子串的起始下标,max表示最长有效括号子串长度,初始值均为0
2.遍历给字符串中的所有字符
2.1若当前字符s[index]为左括号'(',将当前字符下标index入栈(下标稍后有其他用处),处理下一字符
2.2若当前字符s[index]为右括号')',判断当前栈是否为空
2.2.1若栈为空,则start = index + 1,处理下一字符(当前字符右括号下标不入栈)
2.2.2若栈不为空,则出栈(由于仅左括号入栈,则出栈元素对应的字符一定为左括号,可与当前字符右括号配对),判断栈是否为空
2.2.2.1若栈为空,则max = max(max, index-start+1)
代码:
1 class Solution { 2 public int longestValidParentheses(String s) { 3 if(s==null||s.length()==0) 4 return 0; 5 6 int start=0; 7 int max=0; 8 char[] arrr=s.toCharArray(); 9 LinkedList<Integer> list=new LinkedList<>(); 10 for(int i=0;i<s.length();i++) 11 { 12 if(arrr[i]=='(') 13 list.push(i); 14 else 15 { 16 if(!list.isEmpty()) 17 { 18 list.pop(); 19 if(list.isEmpty()) 20 { 21 max=Math.max(max, i-start+1); 22 } 23 else 24 max=Math.max(max, i-list.peek()); 25 } 26 else 27 { 28 start=i+1; 29 continue; 30 } 31 32 } 33 } 34 return max; 35 36 } 37 }