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) {
    	if (s == null) {
    		return 0;
    	}
    	int longest = 0;
    	for (int i = 0; i < s.length(); i++) {
    		int right = 0;
    		int len = 0;
    		int res = 0;
    		for (int j = i; j >= 0; j--) {
    			if (s.charAt(j) == ')') {
    				right++;
    			} else {
    				right--;
    				if (right < 0) {
    					break;
    				}
    				len += 2;
    				if (right == 0) {
    					res = len;
    				}
    			}
    		}
    		if (longest < res) {
    			longest = res;
    		}
    	}
    	return longest;
    }
}

 

你可能感兴趣的:(long)