2022-09-27 10:58:48 +00:00
|
|
|
package ch.nuth.zhaw.exbox;
|
|
|
|
|
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
|
|
|
import java.util.regex.MatchResult;
|
|
|
|
import java.util.regex.Matcher;
|
|
|
|
import java.util.regex.Pattern;
|
|
|
|
|
|
|
|
public class BracketServer implements CommandExecutor {
|
2022-09-28 07:36:34 +00:00
|
|
|
private static Pattern bracketPattern = Pattern.compile("(/\\*|\\*/|[(){}\\[\\]<>])");
|
2022-09-27 10:58:48 +00:00
|
|
|
|
|
|
|
private static Map<String, String> bracketPairs;
|
|
|
|
|
|
|
|
public BracketServer() {
|
|
|
|
super();
|
2022-10-11 11:17:58 +00:00
|
|
|
|
2022-09-28 07:36:34 +00:00
|
|
|
bracketPairs = new HashMap<>() {
|
|
|
|
{
|
|
|
|
put("(", ")");
|
|
|
|
put("[", "]");
|
|
|
|
put("{", "}");
|
|
|
|
put("<", ">");
|
|
|
|
put("/*", "*/");
|
|
|
|
}
|
|
|
|
};
|
2022-09-27 10:58:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public String execute(String command) throws Exception {
|
|
|
|
return Boolean.toString(checkBrackets(command)) + "\n";
|
|
|
|
}
|
|
|
|
|
|
|
|
public boolean checkBrackets(String expression) {
|
|
|
|
ListStack openBrackets = new ListStack();
|
|
|
|
Matcher matcher = bracketPattern.matcher(expression);
|
|
|
|
Iterable<MatchResult> results = () -> matcher.results().iterator();
|
|
|
|
|
|
|
|
for (MatchResult result : results) {
|
|
|
|
if (bracketPairs.keySet().contains(result.group())) {
|
|
|
|
openBrackets.push(result.group());
|
2022-10-11 11:17:58 +00:00
|
|
|
} else if (!openBrackets.isEmpty() &&
|
|
|
|
result.group().equals(bracketPairs.get(openBrackets.peek()))) {
|
2022-09-27 10:58:48 +00:00
|
|
|
openBrackets.pop();
|
|
|
|
} else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return openBrackets.isEmpty();
|
|
|
|
}
|
|
|
|
}
|