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