# LeetCode – Longest Valid Parentheses (Java)

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.

Java Solution

A stack can be used to track and reduce pairs. Since the problem asks for length, we can put the index into the stack along with the character. For coding simplicity purpose, we can use 0 to respresnt ( and 1 to represent ).

This problem is similar with Valid Parentheses, which can also be solved by using a stack.

```public int longestValidParentheses(String s) { Stack<int[]> stack = new Stack<>(); int result = 0;   for(int i=0; i<s.length(); i++){ char c = s.charAt(i); if(c==')'){ if(!stack.isEmpty() && stack.peek()[0]==0){ stack.pop(); result = Math.max(result, i-(stack.isEmpty()?-1:stack.peek()[1])); }else{ stack.push(new int[]{1, i}); } }else{ stack.push(new int[]{0, i}); } }   return result; }```

### 12 thoughts on “LeetCode – Longest Valid Parentheses (Java)”

1. I’m sorry but I don’t understant why you use Math.max(). I get always a good result by just writing => result = i-(stack.isEmpty()?-1:stack.peek()[1]));
Could you explain? Thank’s

2. yes

3. is this a valid sequence – (())…will the length be 4?

4. ``` public static int longestValidParentheses(String s) { int validLength = 0; int openParenthesisCount = 0; int maxValidLength = 0;```

``` ```

``` for (int i = 0; i 0) { openParenthesisCount--; validLength = validLength + 2; } else { validLength = 0; openParenthesisCount = 0; } } if(maxValidLength < validLength) { maxValidLength = validLength; } } return maxValidLength; } ```

5. this solution return the last valid string length
for ex: “))(((()))))()” will return 2

6. simpler version

public static int longestValidParentheses(String s) {
if (s.length() == 0 || s.length() == 1) return 0;
Stack stack = new Stack();
int result = 0;
int length = 0;
for (int i = 0; i <= s.length() – 1; i++) {
char c = s.charAt(i);
if (stack.isEmpty() && c == ')') {
length = 0;
continue;
}
if (c == '(') {
stack.push(c);
} else {
stack.pop();
length += 2;
result = Math.max(length, result);
}
}

return result;
}

7. Here is one implementation with no extra space required (space complexity is O(1)). Time complexity is the same (O(N)): http://ideone.com/v2ST3z

8. Does it work for (())(() . The answer should be 4. But i guess its giving 6

9. In case if you also want to print the output string as well with length, this is exactly how its described in the validatePattern method.

``` import java.util.*; public class LongestValidParenthesis { private static Map map = new HashMap(); static { map.put('(', ')'); } private static String printLongest(String input) { Stack stack = new Stack(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < input.length(); i++) { char ch = input.charAt(i); // cannot start with ) string. if (stack.empty() && map.containsValue(ch)) { continue; } if (map.containsKey(ch)) { stack.push(ch); } else if (map.containsValue(ch)) { if (!stack.empty() && map.get(stack.peek()) == ch) { sb = sb.insert(0, stack.pop()); sb = sb.append(ch); } else { continue; } } } return sb.toString(); } public static void main(String[] args) { String input = "(()"; String result = printLongest(input); System.out.println("output string: " + result); System.out.println("length: " + result.length()); } } ```

10. public class Solution {

public int longestValidParentheses(String s) {

int best = 0;

Stack stack = new Stack();

for(int i=0;i<s.length();i++){

char c = s.charAt(i);

if(c=='('){

stack.push(c);

}else if(stack.empty()){

}else{

stack.pop();

if(stack.empty()){

}

}

}

return best;

}

}

11. Good Job.. Special thing is that trick of using i(index) and 0|1 for extra ‘)’, to cover this kind of testcases: ())()() :Sol is 4.