標籤:leetcode
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.
題意:給定一串包含括弧的字串,求字長有效括弧串。能順序匹配的。這一題剛開始想好久~~,用stack來做題,很容易求出字串中所有有效括弧長度。但是如何求有效子串呢?如果我們能找出無效括弧的index,將有效index減去上一個無效的index,那麼就是該字元的有效子串。弄清楚這一點求最大的有效字串也會變得很容易。
public int longestValidParentheses(String s) { if(s==null)return 0; int len=s.length(); int i=0; Stack<Integer> stack=new Stack<Integer>(); char ch; int res=0; while(i<len) { ch=s.charAt(i); if(ch=='(') stack.push(i);//我們變換思路,將括弧的index入棧 else { if(!stack.isEmpty()&&s.charAt(stack.peek())=='(')//如果是’)',且與stack頂括弧匹配時,彈出 { stack.pop(); res=Math.max(stack.isEmpty()?i+1:i-stack.peek(),res);//為空白的話,證明前面沒有無效括弧,將i+1;不為空白的,前面有無效字元,減去無效字元的index }else { stack.push(i); } } i++; } return res; }
[Java] LeetCode32 Longest Valid Parentheses