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;
}
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Bonsai

    yes

  • mash

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

  • Swat


    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;
    }

  • Melad Ezzat

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

  • Jangku

    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;
    }

  • Matias SM

    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

  • Geek Coder

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

  • Ankit Shah

    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());
    }
    }

  • Omar Edgardo Lugo Sánchez

    public class Solution {

    public int longestValidParentheses(String s) {

    int resultado = 0;

    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()){

    resultado=0;

    }else{

    stack.pop();

    resultado+=2;

    if(stack.empty()){

    best = Math.max(resultado, best);

    }

    }

    }

    return best;

    }

    }

  • typing..

    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.