Longest Valid Parentheses

原创 2015年11月19日 15:58:39

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.

public class Solution {
    public int longestValidParentheses(String s) {
        Stack<int[]> record = new Stack<>();
        int max = 0;
        for(int i = 0; i < s.length(); i++){
            int currentSymbol = s.charAt(i) == '('? 1 : 2;
            if(currentSymbol == 1){
                record.push(i * 10 + 1);
            }
            else{
                if(record.empty() || record.peek() % 10 == 2)
                    record.push(i * 10 + 2);
                else{
                    record.pop();
                    int localLength = 0;
                    if(record.empty()){
                        localLength = i + 1;
                    }
                    else{
                        localLength = i - record.peek() / 10;
                    }
                    
                    max = Math.max(max, localLength);
                }
            }
        }
        return max;
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Leetcode 32. Longest Valid Parentheses

问题描述 Given a string containing just the characters '(' and ')', find the length of the longe...

[leetcode]Longest Valid Parentheses

题目介绍: Given a string containing just the characters '(' and ')', find the length of the longe...

longest valid parentheses--LeetCode

Given a string containing just the characters '(' and ')', find the length of the longest valid (wel...

Leetcode: Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...

leetcode 032 Longest Valid Parentheses

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

LeetCode_32---Longest Valid Parentheses

Longest Valid Parentheses  Total Accepted: 36685 Total Submissions: 176120My Submissions Quest...

leetcode Longest Valid Parentheses

这个星期没有做题,跑出去玩了一圈。投个实习感觉被鄙视了,回来继续学习算了。 Given a string containing just the characters '(' and...

[LeetCode]32.Longest Valid Parentheses

题目Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (w...

[LeetCode] 最长合法括号 longest valid parentheses

给你一个字符串,该字符串仅仅包含 '(‘ 和 ')',找出最长的合法括号子串。例如:"(()" 的最长合法括号子串是 “()” ,长度是2。")()())" 的最长合法括号子串是 “()()” ,长度...

leetcode 32. Longest Valid Parentheses

leetcode 32. Longest Valid Parentheses 算法就是从左向右扫描,遇到左括号就入栈,遇到右括号有三种情况: 1.栈顶是左括号,那么用2取代那个左括号,这时如果栈顶下边...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)