LeetCode:Longest Valid Parentheses

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.

承认自己有点2了。一开始题目没看清楚就写了。以为求的是所有有效括号数,没有求Longest.

方法很简单。用一个record数组,长度和s一样,记录每个位置的符号是否有匹配,有匹配的为true。最后就是查找数组最长的true值。


public class Solution {
    public int longestValidParentheses(String s) {
        int maxlen = 0;
        if(s==null||s.length() == 0)return maxlen;
        char[] ch = s.toCharArray();
        int length = ch.length;
        Stack<Integer> lefts = new Stack<Integer>();
        boolean[] record = new boolean[length];
        int i = 0;
        while(i<length)
        {
            if(ch[i] == '(')
            {
                lefts.push(i);
            }
            else
            {
                if(!lefts.isEmpty())
                {
                    record[i] = true;
                    record[lefts.pop()] = true;
                }
            }
            i++;
        }
        maxlen = maxConNum(record);
        return maxlen;
    }
    public int maxConNum(boolean[] b)
    {
        int length = b.length;
        if(b==null||length == 0)return length;
        int i = 0;
        int max = 0;
        while(i<length)
        {
            int num = 0;
            while(i<length&&b[i])
            {
                num++;
                i++;
            }
            max = max>num?max:num;
            i++;
        }
        return max;
    }
}

posted on 2014-06-09 16:52  JessiaDing  阅读(103)  评论(0编辑  收藏  举报