educative.io

Educative

It appears there is a simpler solution with one pass

If I’m not mistaking there is a simpler solution to this problem with one path.

public static int longestValidParentheses(String s) {	
	int count = 0;
	int len = 0;
	int max = 0;
	for(int i = 0; i < s.length(); i++) {
		if(s.charAt(i) == '(') {
			count++;
			len++;
		}
		else if(count > 0 && s.charAt(i) == ')') {
			count--;
			len++;
		}
		else if(count == 0 && s.charAt(i) == ')') {
			if(max < len) {
				max = len;
				len = 0;
			}
		}
	}

	if(count > 0) {
		return Math.max(max, len - count);
	}

	return max;
}

Hello @Peter_Litvak ,
Can you please share course and lesson name?