leetcode-32. Longest Valid Parentheses

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.

这题应该怎么想,首先括号有一些自身的特性,比如说只有有左括号则必须有右括号,如果括号不成双则说明无效。所以所有这种判断括号有效性的题目都可以用栈来解决,遇到左括号就压入栈,遇到右括号就弹出一个栈(当然还要判断栈的元素数量)。

这里的思路就是用一个指针从左往右指,然后看当前位置是否是左括号,

  • 如果是左括号就将当前位置压人栈,
  • 如果是右括号就判断当前栈是否为空,
    • 如果是空则说明之前数据违法了,那就从当前位置开始判断之后的括号是否有效。
    • 如果不是则抛出一个左括号与当前指针的右括号相消,这时在判断栈是否为空。
      • 如果这时栈为空了,则说明以当前的left为节点的区域已经判断完毕。更新一下max;
      • 如果这时栈不为空,则说明以当前的i为右节点,栈顶元素为做节点的区域是当前的最大正确区域。

非常漂亮的解法,也没想出来,我想出来的没这么快。贴一下来源

答案来源

public class Solution {
    public int longestValidParentheses(String s) {
        if(s==null || s.length()<1) return 0;
        int max = 0;
        int left = -1;
        Stack<Integer> sta = new Stack<Integer>();
        for(int i = 0 ; i < s.length(); i++){
            if(s.charAt(i)=='('){
                sta.push(i);
            }else{
                if(sta.isEmpty()) left = i;
                else{
                    sta.pop();
                    if(sta.isEmpty()) max=Math.max(max,i-left);
                    else max=Math.max(max,i-sta.peek());
                }
            }
        }
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值