Leetcode32 Longest Valid Parentheses

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[n];
        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;   
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值