Leetcode 32.最长有效括号

最长有效括号

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

示例 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 }

原文地址:https://www.cnblogs.com/kexinxin/p/10163001.html