Leetcode 32.最長有效括號
阿新 • • 發佈:2018-12-23
最長有效括號
給定一個只包含 '(' 和 ')' 的字串,找出最長的包含有效括號的子串的長度。
示例 1:
輸入: "(()"
輸出: 2
解釋: 最長有效括號子串為 "()"
示例 2:
輸入: ")()())"
輸出: 4
解釋: 最長有效括號子串為 "()()"
設定兩個指標,一個表示左括號open的個數 ,另一個表示右括號close的個數。
方法:兩次遍歷操作,第一次從前往後遍歷,第二次從後向前遍歷。 因此時間複雜度為O(n)
1.從左向右掃描,當遇到左括號時,open++,當遇到右括號時,close++
如果open==close,那麼需要對最長長度max進行更新操作 max = Math.max(max , 2*open)
如果 close > open ,說明右括號個數大於左括號個數,已經不滿足合法性,則重新設定open=0, close=0
2.從右向左掃描,當遇到右括號時close++,當遇到左括號時,open++
如果close==open,那麼更新max即 max = Math.max(max , 2*close)
如果open>close ,說明右括號個數大於左括號個數,已經不滿足合法性,則重新設定open=0 ,close =0
1 class Solution { 2 public int longestValidParentheses(String s) { 3 int right=0,left=0,ans=0; 4 int len=s.length(); 5 for(int i=0;i<len;i++){ 6 if(s.charAt(i)=='(') 7 left++; 8 else 9 right++;10 if(left==right){ 11 ans=Math.max(ans,2*right); 12 }else if(right>left) 13 left=right=0; 14 } 15 left=right=0; 16 for(int i=len-1;i>=0;i--){ 17 if(s.charAt(i)==')') 18 right++; 19 else 20 left++; 21 if(right==left) 22 ans=Math.max(ans,2*left); 23 else if(left>right) 24 left=right=0; 25 } 26 return ans; 27 } 28 }