LeetCode 32. Longest Valid Parentheses(栈)

题目来源:https://leetcode.com/problems/longest-valid-parentheses/

问题描述

32. Longest Valid Parentheses

Hard

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Example 1:

Input: "(()"

Output: 2

Explanation: The longest valid parentheses substring is "()"

Example 2:

Input: ")()())"

Output: 4

Explanation: The longest valid parentheses substring is "()()"

------------------------------------------------------------

题意

给出一个由’(‘和’)’组成的序列,求序列中最大合法括号匹配子列的长度。

------------------------------------------------------------

思路

用栈来模拟括号匹配的过程,一篇扫描过后栈中剩余的字符是无法匹配的括号,也就是合法子列之间的分隔符。另开一个栈记录这些每个字符的位置,同样模拟括号匹配的压栈弹栈过程,剩余的位置就是分隔符的位置。用迭代器遍历分隔符的位置,合并可以合并的子列,同时求出最大子列的长度。

------------------------------------------------------------

代码

class Solution {
    public int longestValidParentheses(String s) {
        int n = s.length(), i = 0;
        Stack<Character> stack = new Stack<Character>();
        Stack<Integer> pos = new Stack<Integer>();
        char top = 0, cur = 0;
        for (i=0; i<n; i++)
        {
            cur = s.charAt(i);
            if (!stack.empty())
            {
                top = stack.peek();
                if (top == '(' && cur == ')')
                {
                    stack.pop();
                    pos.pop();
                }
                else
                {
                    stack.push(cur);
                    pos.push(i);
                }
            }
            else
            {
                stack.push(cur);
                pos.push(i);
            }
        }
        pos.add(n);
        Iterator<Integer> iter = pos.iterator();
        int pre = -1, end = -1, max_len = 0;
        while (iter.hasNext())
        {
            end = iter.next();
            max_len = (end-pre-1) > max_len ? (end-pre-1): max_len;
            pre = end;
        }
        return max_len;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值