LeetCode 32 Longest Valid Parentheses(最长合法的括号组合)

 
Problem :已知字符串s,求出其中最长的括号合法组合长度
 
设置两个指针,一个表示左括号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
 
参考代码:
 
package leetcode_50;

/***
 * 
 * @author pengfei_zheng
 * 最长合法的括号问题
 */
public class Solution32 {
    public static int longestValidParentheses(String s) {
        int right = 0 , left = 0, ans = 0;
        int len = s.length();
        for(int i = 0 ; i < len ; i++){
                if(s.charAt(i)=='(')
                    left++;
                else
                    right++;
                if(left == right){
                    ans = Math.max(ans,2*right);
                }
                else if(right>left)
                    left = right = 0;
        }
        left = right = 0;
        for(int i = len-1 ; i >= 0 ; i--){
                if(s.charAt(i)==')')
                    right++;
                else
                    left++;
                if(right == left)
                    ans = Math.max(ans,2*left);
                else if(left>right)
                    left = right = 0;
        }
        return ans;
    }
    public static void main(String[]args){
        String s="()()";
        System.out.println(longestValidParentheses(s));
    }
}
原文地址:https://www.cnblogs.com/zpfbuaa/p/6531746.html