Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed).
For example, given the string “([])[]({})”, you should return true.
Given the string “([)]” or “((()”, you should return false.
There is are Stack implementation currently available in Apex so we can use a List to push and pop characters
Solution
public class Stack {
private List<Object> items {get; set;}
public Stack() {
this.items = new List<Object>();
}
public Integer size() {
return this.items.size();
}
public Boolean isEmpty() {
return size() == 0;
}
public void push(Object itemToPush) {
this.items.add(itemToPush);
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return this.items.remove(size() - 1);
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStackException('Stack is empty');
}
return this.items.get(size() - 1);
}
}
public class EmptyStackException extends Exception {}
public static Map<String, String> mapBrackets(){
Map<String, String> bracketMap = new Map<String, String>();
bracketMap.put('}', '{');
bracketMap.put(')', '(');
bracketMap.put(']', '[');
return bracketMap;
}
public static Boolean checkClosingBrackets(String bracketStr) {
Map<String, String> bracketMap = mapBrackets();
Stack customStack = new Stack();
for (Integer i=0; i < bracketStr.length(); i++){
String str = bracketStr.substring(i,i+1);
System.debug('> ' + str);
if (!bracketMap.containsKey(str)){
customStack.push((String)str);
} else {
String pop = (String)customStack.pop();
String mappedVal = bracketMap.get(str);
if (!mappedVal.equals(pop)){
return false;
}
}
}
if (!customStack.isEmpty()){
return false;
}
return true;
}
Testing
System.debug(checkClosingBrackets('([])[]({})')); //true
System.debug(checkClosingBrackets('([])[]({}')); //false