Valid Parentheses in Java

The challenge

Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it’s invalid.

Examples

"()"              =>  true
")(()))"          =>  false
"("               =>  false
"(())((()())())"  =>  true

Constraints

0 <= input.length <= 100

Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. []{}<>).

The solution in Java code

Option 1:

public class Solution {
  public static boolean validParentheses(String parens) {
        while (parens.contains("(") && parens.contains(")")) {
            parens = parens.replaceAll("\\([^()]*\\)", "");
            if (!parens.matches(".*\\(+.*\\)+.*"))
                break;
        }
        return !parens.contains("(") && !parens.contains(")");
    }
}

Option 2:

public class Solution {
  public static boolean validParentheses(String parens) {
        int stack = 0;
        for(var c : parens.toCharArray()) {
            if (c == '(') ++stack;
            else if (c == ')') {
                if (stack == 0) return false;
                else --stack;
            }
        }
        return stack == 0;
  }
}

Option 3:

public class Solution {
  public static boolean validParentheses(String parens) {
        int count = 0;

        for (int i=0; i<parens.length(); i++) {
          if (parens.charAt(i)=='(') count ++;
          else if (parens.charAt(i)==')') count--;
          if (count<0) return false;
       }
     return count==0;
  }
}

Test cases to validate our solution

import org.junit.Test;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SolutionTest {
    @Test
    public void sampleTest() {
        // assertEquals("expected", "actual");
      assertEquals(true,Solution.validParentheses( "()" ));  
      assertEquals(false,Solution.validParentheses( "())" ));
      assertEquals(true,Solution.validParentheses( "32423(sgsdg)" ));  
      assertEquals(false,Solution.validParentheses( "(dsgdsg))2432" ));
      assertEquals(true,Solution.validParentheses( "adasdasfa" ));
    }
}

Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments