I am trying to write 2 methods that can sort a string of brackets using only 1 stack and 1 switch statement. I can't get it to work, I am wondering if it may be because of cases of ' ' in strings? should not default case pick up these or have I understood switch statements wrong? This is where I am right now.
out.println(checkParentheses("({} [()] ({}))")); // should print true
out.println(!checkParentheses("({} [() ({)})")); // should print false
Boolean checkParentheses(String brackets) {
Deque<Character> stack = new ArrayDeque<>();
for( char ch : brackets.toCharArray()) {
if (stack.peek() == matching(ch)) {
stack.pop();
} else {
stack.add(ch);
}
}
return stack.isEmpty();
}
char matching(char ch) {
// char c = (' ');
switch (ch) {
case ')':
return '('; // c = '('
case ']':
return '[';
case '}':
return '{';
default:
// return c;
throw new IllegalArgumentException("No match found");
}
}
Basically, checkParentheses should be as simple as follows:
public static boolean checkParentheses(String str) {
if (null == str || str.isEmpty()) {
return true;
}
Deque<Character> stack = new ArrayDeque<>();
for (char c : str.toCharArray()) {
if (openingBracket(c)) {
stack.push(c);
} else if (closingBracket(c)) {
if (stack.isEmpty() || matchingBracket(c) != stack.pop()) {
return false;
}
} // else ignore non-bracket char quietly
}
return stack.isEmpty();
}
Then additional methods may look as follows using switch statement:
static boolean openingBracket(char c) {
switch (c) {
case '(': case '[': case '{': case '<':
return true;
default:
return false;
}
}
static boolean closingBracket(char c) {
switch (c) {
case ')': case ']': case '}': case '>':
return true;
default:
return false;
}
}
static char matchingBracket(char c) {
switch (c) {
case ')': return '(';
case ']': return '[';
case '}': return '{';
case '>': return '<';
default:
throw new IllegalArgumentException("Bad character found instead of closing bracket: " + c);
}
}
Then the output of the tests is as follows:
System.out.println(checkParentheses("({} [()] ({}))")); // true, balance ok
System.out.println(!checkParentheses("({} [() ({)})")); // true, NOT balanced