Add a server for checking brackets
This commit is contained in:
parent
b13632ccc8
commit
8aa71b1ee5
1 changed files with 45 additions and 0 deletions
45
app/src/main/java/ch/nuth/zhaw/exbox/BracketServer.java
Normal file
45
app/src/main/java/ch/nuth/zhaw/exbox/BracketServer.java
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
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 {
|
||||||
|
private static Pattern bracketPattern = Pattern.compile("(/\\*|\\*/|[(){}\\[\\]])");
|
||||||
|
|
||||||
|
private static Map<String, String> bracketPairs;
|
||||||
|
|
||||||
|
public BracketServer() {
|
||||||
|
super();
|
||||||
|
bracketPairs = new HashMap<>();
|
||||||
|
bracketPairs.put("(", ")");
|
||||||
|
bracketPairs.put("[", "]");
|
||||||
|
bracketPairs.put("{", "}");
|
||||||
|
bracketPairs.put("/*", "*/");
|
||||||
|
}
|
||||||
|
|
||||||
|
@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());
|
||||||
|
} else if (result.group().equals(bracketPairs.get(openBrackets.peek()))) {
|
||||||
|
openBrackets.pop();
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return openBrackets.isEmpty();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue