问题描述:
给定字符串,仅包含左括号‘(‘和右括号‘)‘,它可能不是括号匹配的,设计算法,找出最长的括号字串,并返回字串的长度。
如:
((): 2
()(): 4
()(()):6
(()()): 6
思路分析:
Code :
/** * 给定一个字符串,返回字符串中括号的最大匹配长度 * @param s * @return */ public int getLongestParenthese(String s) { char[] ch = s.toCharArray(); Stack<Integer> stack = new Stack<Integer>(); int start = -1; int max = 0; for(int i=0; i<ch.length; i++) { if(ch[i] == ‘(‘) stack.push(i); else { if(stack.isEmpty()) start = i; else { stack.pop(); if(stack.isEmpty()) max = Math.max(max, i-start); else max = Math.max(max, i-stack.peek()); } } } return max; }
原文:http://www.cnblogs.com/little-YTMM/p/5448741.html