2014年2月25日星期二

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.

public class Solution {
    public int longestValidParentheses(String s) {
        int max = 0;
        if(s==null) {
            return max;
        }
        int valid = 0;
        Stack<Integer> stk = new Stack<Integer>();
        for(int i=0;i<s.length();i++) {
            char c = s.charAt(i);
            if(c==')') {
                if(stk.isEmpty()) {
                    valid = i+1;
                } else {
                    stk.pop();
                    if(stk.isEmpty()) {
                        max = Math.max(max, i-valid+1);
                    } else {
                        max = Math.max(max, i-stk.peek());
                    }
                }
            } else {
                stk.push(i);
            }
        }
        return max;
    }
}

public class Solution {
    public int longestValidParentheses(String s) {
        if(s==null || s.length()==0) {
            return 0;
        }
        Stack<Integer> stk = new Stack<Integer>();
        int tag[] = new int[s.length()];
        for(int i=0;i<s.length();i++) {
            char c = s.charAt(i);
            if(c=='(') {
                stk.push(i);
            } else {
                if(!stk.isEmpty()) {
                    int j = stk.pop();
                    tag[i] = 1;
                    tag[j] = 1;
                } else {
                }
            }
        }
        int max = 0;
        int cur = 0;
        for(int i=0;i<tag.length;i++) {
            int n = tag[i];
            if(n==1) {
                cur += 1;
            } else {
                cur =0;
            }
            max = Math.max(cur, max);
        }
        return max;
    }
}

没有评论:

发表评论