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 Algorithm 032. Longest Valid Parentheses

Leetcode Algorithm 032. Longest Valid Parentheses 给定一个只含有'('和')'的字符串,求出符合括号匹配要求的最长子串(不是子序列)。...

leetcode-32. Longest Valid Parentheses

leetcode-32. Longest Valid Parentheses - 如果是左括号就将当前位置压人栈, - 如果是右括号就判断当前栈是否为空, - 如果是空则说明之前数据违法...

leetcode 32 -- Longest Valid Parentheses

Longest Valid Parentheses 题目: Given a string containing just the characters ‘(’ and ‘)’, find t...

[LeetCOde32]Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (we...
  • sbitswc
  • sbitswc
  • 2014年06月15日 00:17
  • 595

32. Longest Valid Parentheses

主要参考:http://blog.csdn.net/feliciafay/article/details/20686595,该方法的时间复杂度为O(n)。 C++代码:class Solution ...

LeetCode - Longest Valid Parentheses

https://leetcode.com/problems/longest-valid-parentheses/ Given a string containing just the cha...

leetcode 32. Longest Valid Parentheses——(use stack)

import java.util.Stack; //Given a string containing just the characters '(' and ')', find the lengt...

leetcode笔记:32.Longest Valid Parentheses

题目要求:string s 只包含 '(' 和 ‘)’ 寻找最长valid长度。 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 vali...

Leetcode32:Longest Valid Parentheses

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (wel...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Longest Valid Parentheses
举报原因:
原因补充:

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