Longest Valid Parentheses

来源:互联网 发布:黑龙江大学网络教育 编辑:程序博客网 时间:2024/05/05 12:31

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
原创粉丝点击