您的位置:首页 > 其它

LongestValidParentheses, 求最长合法括号子串长度-----同类问题ValidParentheses,GenerateParentheses

2016-06-08 19:41 666 查看
问题描述:求括号字符串中最长合法子串长度。例如:()((),返回2,而不是4.

算法分析:还是利用栈,和判断合法括号对是一样的。

public static int longestValidParentheses(String s) {
Stack<int[]> stack = new Stack<int[]>();
int result = 0;

for(int i=0; i<=s.length()-1; i++)
{
char c = s.charAt(i);
if(c=='(')//如果是左括号
{
int[] a = {i,0};
stack.push(a);
}
else//如果是右括号
{
if(stack.empty()||stack.peek()[1]==1)//如果栈为空或者栈顶元素为右括号
{
int[] a = {i,1};
stack.push(a);
}
else
{
stack.pop();
int currentLen=0;
if(stack.empty())
{
currentLen = i+1;
}
else
{
currentLen = i-stack.peek()[0];
}
result = Math.max(result, currentLen);
}
}
}

return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: