关闭

Longest Valid Parentheses

95人阅读 评论(0) 收藏 举报
分类:

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;
    }
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7792次
    • 积分:823
    • 等级:
    • 排名:千里之外
    • 原创:78篇
    • 转载:2篇
    • 译文:0篇
    • 评论:0条
    文章分类