leetcode-32 Longest Valid Parentheses

问题描述:

Givena string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parenthesessubstring.

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.

 

问题分析:

    题目即找到最长的合法字符串的长度;

    见到左右括号,自然想到使用Stack进行操作;这里寻找最长的子字符串,使用一个技巧,时间复杂度为O(N),空间复杂度为O(N)

1、先遍历整个字符串,将不匹配的字符位置index push进stack;匹配的左右括号弹出;则遍历一遍后剩下的就是不匹配的字符的位置;

2、剩下的操作就是在不匹配字符之间找到最长的长度;由于每个不匹配字符的位置都已经存储到stack中,直接简单地对stack进行遍历即可;

 

代码:

public class Solution {
   public int longestValidParentheses(String s) {
        int length = s.length();
        int longest = 0;
        // 存储未匹配字符的位置
        Stack<Integer> stack = new Stack<>();
        // 先遍历一遍s,将不匹配的字符位置找出来
        for (int i = 0; i < length; i++) {
        // 唯一的匹配情况就是stack不为null,并且对应字符为'('与')',此情况下stack弹出,其他情况均push
            if (!stack.isEmpty() && s.charAt(i) == ')' &&s.charAt(stack.peek()) == '(')
                stack.pop();
            else
                stack.push(i);
        }
        // 计算每个被分割线段;即两个节点之间的数据长度
        int start = 0, end = length; // 这个end可以看做尾后指针
        while (!stack.isEmpty()) {
            start = stack.pop();
            longest = Math.max(longest,end - start - 1);
            end = start;
        }
        // 注意不要漏下减去头前指针的情况
        longest = Math.max(longest,end);
       
        return longest;
   }
}


运行结果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值