LeetCode 32 最长有效括号

暴力解法

每当我们遇到一个 \text{‘(’}‘(’ ,我们把它放在栈顶。对于遇到的每个 \text{‘)’}‘)’ ,我们从栈中弹出一个 \text{‘(’}‘(’ ,如果栈顶没有 \text{‘(’}‘(’,或者遍历完整个子字符串后栈中仍然有元素,那么该子字符串是无效的。这种方法中,我们对每个偶数长度的子字符串都进行判断,并保存目前为止找到的最长的有效子字符串的长度。

public class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                stack.push('(');
            } else if (!stack.empty() && stack.peek() == '(') {
                stack.pop();
            } else {
                return false;
            }
        }
        return stack.empty();
    }
    public int longestValidParentheses(String s) {
        int maxlen = 0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = i + 2; j <= s.length(); j+=2) {
                if (isValid(s.substring(i, j))) {
                    maxlen = Math.max(maxlen, j - i);
                }
            }
        }
        return maxlen;
    }
}

栈解法

与找到每个可能的子字符串后再判断它的有效性不同,我们可以用栈在遍历给定字符串的过程中去判断到目前为止扫描的子字符串的有效性,同时能的都最长有效字符串的长度。我们首先将 -1−1 放入栈顶。

对于遇到的每个 \text{‘(’}‘(’ ,我们将它的下标放入栈中。
对于遇到的每个 \text{‘)’}‘)’ ,我们弹出栈顶的元素并将当前元素的下标与弹出元素下标作差,得出当前有效括号字符串的长度。通过这种方法,我们继续计算有效子字符串的长度,并最终返回最长有效子字符串的长度。
转自LeetCode官方题解

https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode/

public static int longestValidParentheses(String s) {
        int maxlen=0;
        Stack<Integer> stack=new Stack<>();
        stack.push(-1);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i)=='(')
            {
                stack.push(i);
            }
            else {
                stack.pop();
                //(((
                if (stack.empty())
                {
                    stack.push(i);
                }
                else
                {
                    maxlen=Math.max(maxlen,i-stack.peek());
                }
            }
        }
        return maxlen;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值