您的位置:首页 > 其它

[算法基础练习]最长括号匹配

2017-04-27 09:46 260 查看
/**最长括号匹配
* <pre>
* 输入的字符串只包含左括号,右括号
* 1.起始匹配的位置start=-1,匹配的最长长度ml=0
* 2.遍历第i个字符c
* 3.如果c是左括号,压栈
* 4.如果c是右括号,则与栈顶元素进行匹配
*   4.1 如果栈为空,则此时的c无法匹配,更新start=i,为下一次匹配做准备
*   4.2 如果栈非空,则出栈
*      出栈后为空,则更新ml-max(i-start,ml)
*      出栈后不为空,则更新ml=max(i-t),t为栈顶元素
*  遍历n个字符,时间复杂度为O(n)
* </pre>
* @param s
* @return
*/
public int getMaxMatchLength(String s){
if(s==null||s.length()==0){
return 0;
}
Stack<Integer> stack = new Stack<Integer>();
int start = -1;
int ml = 0;
for(int i=0;i<s.length();i++){
String c = s.substring(i, i+1);
if(c.equals("(")){
stack.push(i);
}else if(stack.empty()){//4.1
start = i;
}else{
stack.pop();
if(stack.isEmpty()){//4.2
ml = ml<i-start?i-start:ml;
}else{//4.2
int t = stack.peek();
ml = ml<i-t?i-t:ml;
}
}

}
return ml;
}
@Test
public void test(){
Assert.assertEquals(getMaxMatchLength("(())"), 4);
Assert.assertEquals(getMaxMatchLength("((()))"), 6);
Assert.assertEquals(getMaxMatchLength("(()"), 2);
Assert.assertEquals(getMaxMatchLength("()())"), 4);
Assert.assertEquals(getMaxMatchLength("()()()"), 6);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: