Determine the order of braces is valid using Java

1 min read 330 words

The challenge

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

All input strings will be nonempty, and will only consist of parentheses, brackets and curly braces: ()[]{}.

What is considered Valid?

A string of braces is considered valid if all braces are matched with the correct brace.

Examples

"(){}[]"   =>  True
"([{}])"   =>  True
"(}"       =>  False
"[(])"     =>  False
"[({})](]" =>  False

The solution in Java code

Option 1:

import java.util.Stack;

public class BraceChecker {
  
  public boolean isValid(String braces) {
    Stack<Character> s = new Stack<>();
    for (char c : braces.toCharArray()) 
      if (s.size() > 0 && isClosing(s.peek(), c)) s.pop(); 
      else s.push(c);
    return s.size() == 0;
  }
  
  public boolean isClosing(char x, char c) {
    return (x == '{' && c == '}') || (x == '(' && c == ')') || (x == '[' && c == ']');
  }
  
}

Option 2:

public class BraceChecker {

  public boolean isValid(String braces) { 
    String b = braces;
    System.out.println(braces);   
    for(int i=0;i<braces.length()/2;i++)
    {
      b = b.replaceAll("\\(\\)", "");
      b = b.replaceAll("\\[\\]", "");
      b = b.replaceAll("\\{\\}", "");
      if(b.length() == 0)
        return true;
    }
    return false;
  }
}

Option 3:

public class BraceChecker {
  public boolean isValid(String s) {
    int x = s.length();
    s = s.replaceAll("\\(\\)|\\[\\]|\\{\\}","");
    return s.length() == x ? false : s.length() == 0 || isValid(s);
  }
}

Option 4:

public class BraceChecker {

  public boolean isValid(String brackets) {
    while(brackets.indexOf("{}")!=-1||brackets.indexOf("[]")!=-1||brackets.indexOf("()")!=-1) {
      brackets = brackets.replace("{}","");
      brackets = brackets.replace("[]","");
      brackets = brackets.replace("()","");
      }
    return brackets.isEmpty();
  }

}

Test cases to validate our solution

import static org.junit.Assert.*;
import org.junit.Test;

public class BraceCheckerTests {

  private BraceChecker checker = new BraceChecker();

  @Test
  public void testValid() {
    assertEquals(true, checker.isValid("()"));
    assertEquals(true, checker.isValid("[]"));
    assertEquals(true, checker.isValid("{}"));
    assertEquals(true, checker.isValid("(){}[]"));
    assertEquals(true, checker.isValid("([{}])"));
    assertEquals(true, checker.isValid("({})[({})]"));
    assertEquals(true, checker.isValid("(({{[[]]}}))"));
    assertEquals(true, checker.isValid("{}({})[]"));
  }
  
  @Test
  public void testInvalid() throws Exception {
    assertEquals(false, checker.isValid("[(])"));
    assertEquals(false, checker.isValid("(}"));
    assertEquals(false, checker.isValid("(})"));
    assertEquals(false, checker.isValid(")(}{]["));
    assertEquals(false, checker.isValid("())({}}{()][]["));
    assertEquals(false, checker.isValid("(((({{"));
    assertEquals(false, checker.isValid("}}]]))}])"));
  }

}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts