leetcode--32.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.


分析:


给定一个字符串只包含字符'(' ')',找到最长的有效长度(形成)括号内的子串。


“(()”,最长有效括号子串是“()”,其长度= 2。
另一个例子是“)()())”,其中最长的子串是“有


效的括号()()”,其长度= 4。


本题使用栈stack,不是用来存左右括号的。是来存左括号的index。遍历s。遇到'(',将index压进ss,如果遇


到')',则弹出一个'('如果ss是空,说明这是一个无法匹配的')',记录下start。start里面存放的其实是最后一


个无法匹配的')'。为啥要保存这个值呢?主要是为了计算后面完整的表达式的长度。可以这样理解: “所有无法匹


配的')'”的index其实都是各个group的分界点。


代码:


import java.util.*;
public class Solution {
    public int longestValidParentheses(String s) {
        int k= s.length(); 
        if (k<2) return 0;
        int result = 0;
        int start = -1;
        Stack<Integer> ss = new Stack<Integer>();
        for(int i = 0;i<k;i++){
              if(s.charAt(i)=='('){
                  ss.push(i);
              }else{
                  if(ss.isEmpty()) start = i;
                  else{
                      ss.pop();
                      if(!ss.isEmpty())
                          result = Math.max(i-ss.peek(),result);
                      else
                          result = Math.max(i-start,result);
                  }
              }
        }
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值