Monday, March 4, 2013

[LeetCode] Longest Valid Parentheses

Thought:
Scan from the front. If left == right, update the result. If left < right, set them as zero.
Scan from the end. If left == right, update the result. If left > right, set them as zero.

Code:
public class Solution {
    public int longestValidParentheses(String s) {
        
        int left = 0, right = 0;
        int max = 0;
       
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '(') left++;
            else right++;
            if (left == right) {
                max = Math.max(right + left, max);
            }
            if (left < right) {
                left = 0;
                right = 0;
            }
        }
       
        left = 0; right = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == '(') left++;
            else right++;
            if (left == right) {
                max = Math.max(right + left, max);
            }
            if (left > right) {
                left = 0;
                right = 0;
            }
        }
        return max;
    }
}

No comments:

Post a Comment