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)); } }