Longest Valid Parentheses (Java)

来源:互联网 发布:怎么看淘宝店 编辑:程序博客网 时间:2024/05/18 03:15

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.

注意这道题的stack里面存的不是括号而是索引。这道题的标签中有动态规划,下次写注意一下动态规划的写法。

Source

public class Solution {    public int longestValidParentheses(String s) {char a;Stack<Integer> st = new Stack<Integer>();//*****int p = 0;int cnt = 0;for(int i = 0; i < s.length(); i++){a = s.charAt(i);if(a == '('){st.push(i);}else if(a == ')'){if(st.size() == 0){  //也可以用isEmptyp = i + 1;}else{st.pop();if(st.isEmpty()){cnt = Math.max(i - p + 1, cnt);}else{cnt = Math.max(i - st.peek(), cnt);}} }}return cnt;    }}


Test

    public static void main(String[] args){    String s = "(()";        System.out.println(new Solution().longestValidParentheses(s));    }


0 0
原创粉丝点击