(java)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.


解题思路:

这道题跟之前的一道题比较像,所以我的做法就是用栈的方式,如果当前的是')'而栈顶是'(',就对栈顶进行pop操作。反之将当前的char放入栈中。

这道题比较麻烦的就是,要来计算最大子串。不能单纯的看最后栈的存储量来决定,而是要看栈中存储的char在字符串中的位置。所以我就进行了相应的修改。用一个栈来存储char,一个栈来储存对应的index。(其实也可以只用一个存储index的栈,或者弄一个map什么的)。在每次要将char存入到栈中时,判断当前Index减去栈顶index是否大于1,大于1证明有子串存在,进行最大子串更新。


public class Solution {
    public int longestValidParentheses(String s) {
        int result = 0;
		int len1 = 0;
		int len2 = 0;
        Stack<Character> sstack = new Stack<Character>();
        Stack<Integer> istack = new Stack<Integer>();
        for(int i = 0;i<s.length();i++)
        {
        	char sub = s.charAt(i);
        	//匹配,进行pop操作
        	if(!sstack.isEmpty() && sstack.peek() == '(' && sub == ')')
        	{
        			sstack.pop();
        			istack.pop();
        	}
        	else
        	{
        		sstack.push(sub);
        		//更新最长子串
        		if(istack.isEmpty())
        			result = Math.max(result, i);
        		else if(i-istack.peek()-1>0)
        			result = Math.max(result, i-istack.peek()-1);
            	istack.push(i);
        	}
        }
        if(!istack.isEmpty())
        	result = Math.max(s.length()-istack.peek()-1,result);
        else
        	result = s.length();
        return result;
    }
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值