Leetcode #32. Longest Valid Parentheses 最长括号对 结题报告

1 结题思想

题目会给出一定的“((())))”等的括号对,问你说最长的有效括号对是多长?

这道题,需要用Stack,并且不能单纯的统计(或),且出栈,其大致有如下的规则:

1、遇到(要压栈当前位置
2、遇到)时,如果还有(在栈中,那么计算此个括号对的长度
3、如果)时,如果没有(在栈中,那么检查上一次匹配开始的位置 last,
4、如果)时,没有(在栈中,那么last就需要重置,这点和3相关

总结:
需要记录上一次匹配成功的位置这是重点,重点是Stack空了之后的处理

2 原题

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.

3 AC解

public class Solution {
    public int longestValidParentheses(String s) {
        Stack<Integer> stack = new Stack<Integer>();
        char chars[]=s.toCharArray();
        int max=0;
        int last=0; //上一个成功匹配的位置
        int n=s.length();
        int m=n-1;
        for(int i=0;i<n;i++){
            if(chars[i]=='(')
                stack.push(i);
            else{
                if(stack.isEmpty()) //需要弹出栈(的时候,却没有数字,所以这个)符号做了一个截断
                    last=i+1;
                else{
                    stack.pop();
                    if(stack.empty()) //为空的时候才能和之前的上一个最开始的位置匹配,不然只能和当前最远的括号比
                        max=Math.max(max,i-last+1);
                    else
                        max=Math.max(max,i-stack.peek());
                }
            }
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值