您的位置:首页 > 其它

Leetcode32 Longest Valid Parentheses

2015-07-28 01:42 302 查看

Longest Valid Parentheses

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.

Solution1

这种题其实没有什么诀窍,多举几个实例渐渐归纳出一些规律出来。这里用栈来实现:

import java.util.Stack;
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int result = 0;
for(int i=0,start=0;i<s.length();i++){
char c = s.charAt(i);
if(c=='(') stack.push(i);//将左括号的位置都记录下来
else{
if(stack.empty()) start = i+1;//更新有可能成为最左边边界的位置
else{
stack.pop();
if(stack.empty()) result = Math.max(result,i-start+1);//说明已经和最左边边界连通起来了
else result = Math.max(result,i-stack.peek());//未和最左边边界连通,但是可以和之前的某个左括号组成有效的括号对
}
}
}
return result;
}
}


Solution2

解法2和解法1思路是一致的,只不过用了更加巧妙的办法使得程序更简短,但是理解起来其实更加复杂了。

import java.util.Stack;
public class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
int result = 0;
for(int i=0,start=0;i<s.length();i++){
if(s.charAt(i)==')'&&!stack.empty()&&s.charAt(stack.peek())=='('){
stack.pop();
result = Math.max(result,i-(stack.empty()?-1:stack.peek()));
}else stack.push(i);//这里相当于将解法一的start位置也存入了stack
}
return result;
}
}


Solution3

动态规划的解法。

import java.util.Stack;
public class Solution {
public int longestValidParentheses(String s) {
int n = s.length();
int[] dp = new int
;
int left = 0, result = 0;
for(int i=0;i<n;i++){
if(s.charAt(i)=='(') left++;//记录当前还有多少左括号未配对
else if(left>0){//若当前有左括号可与当前的右括号配对
dp[i] = 2 + dp[i-1];//先将这个配对的左括号计入
if(i-dp[i]>=0) dp[i] += dp[i-dp[i]];//判断是否和之前的左括号连通了
left--;//未配对左括号数减一
}
result = Math.max(result,dp[i]);
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode