您的位置:首页 > 其它

Longest Valid Parentheses

2015-07-21 22:08 357 查看
Given a string containing just the characters '(' and ')', find the length of the longest

valid (well-formed) parentheses substring.

For "(()", the longest valid parentheses substring is "()", which has length = 2.

Another example is ")()())", where the longest valid parentheses substring is "()()",

which has length = 4.

求最长的括号匹配的子串,如()(()))的匹配长度为6。

解法:

维护一个栈,栈底值为上次匹配失败的位置

首先初始放一个-1入栈代表上次匹配失败的地方为-1

依次扫描字符

若为'(',将位置放入栈中

若为')',若栈中元素大于1个,则代表有'('可匹配,更新最优值,否则更新栈底

显然,对于任意一个部分最长子串,其最后一个字符更新时取的是上一次匹配失败的位置,

故所有部分最长子串取得最优结果

public class Solution {
public int longestValidParentheses(String s) {
int count=0;
Stack<Integer> sk=new Stack<Integer>();
sk.push(-1);
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='(')
sk.push(i);
else{
if(sk.size()>1){
sk.pop();
int tmp=sk.peek();
count=Math.max(count, i-tmp);
}else{
sk.pop();
sk.push(i);
}
}
}
return count;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: