32. 最长有效括号

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

示例 1:

输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"

示例 2:

输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"

package leetCode_5_14;

import java.util.Stack;

/** 
* @author : caoguotao
* @date 创建时间:2019年5月18日 下午9:39:58 
* @version 1.0 
* @parameter  
* @since  
* @return  
*/
public class Solution32_1 {

	public static void main(String[] args) {
		int res = longestValidParentheses("()(())");
		System.out.println(res);
	}
	public static int longestValidParentheses(String s) {
        int a = getLenght(s, '(');
        int b = getLenght(new StringBuilder(s).reverse().toString(), ')');
        return Math.max(a, b);
    }

    private static int getLenght(String s, char ch) {
        int max = 0;
        int count = 0;
        int c = 0;
        for (int i = 0; i < s.length(); i++) {
            if (ch == s.charAt(i)) {
                c++;
            } else {
                if (--c < 0) {
                    count = 0;
                    c = 0;
                } else {
                    count += 2;
                    if (c == 0) {
                        if (count > max) max = count;
                    }
                }
            }
        }
        return max;
    }
}

 

你可能感兴趣的:(leetCode)