10/13/2012

Longest Valid Parentheses

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 n = s.countgth();
        int maxCount = 0;
        int lb = 0;
        int count = 0;
        for(int i = 0; i < n; i++){
            if(s.charAt(i) == '('){
                lb++;
                count++;
            }
            if(s.charAt(i) == ')') {
                lb--;
                count++;
            }
            if(lb == 0 && count > maxCount) {
                maxCount = count;
            }
            else if(lb < 0){
                //invalid
                lb = 0;
                count = 0;
            }
        }
        int rb = 0;
        count = 0;
        for(int i = n-1; i >= 0; i--) {
            if(s.charAt(i) == ')'){
                rb++;
                count++;
            }
            if(s.charAt(i) == '(') {
                rb--;
                count++;
            }
            if(lb == 0 && count > maxCount) {
                maxCount = count;
            }
            else if(lb < 0){
                //invalid
                rb = 0;
                count = 0;
            }
        }
        return maxCount;
    }
}

No comments:

Post a Comment