Solved Task 2

This commit is contained in:
schrom01 2022-09-27 14:11:41 +02:00
parent d00d56bbee
commit 6ee5e173c4
2 changed files with 34 additions and 15 deletions

View File

@ -32,5 +32,8 @@ public class ADS1_3_test {
//new Tests:
test("(",false);
test(")",false);
test("<(<>)>",true);
test("<(<)>>",false);
}
}

View File

@ -1,7 +1,18 @@
package ch.zhaw.ads;
import org.junit.platform.engine.support.discovery.SelectorResolver;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class BracketServer implements CommandExecutor {
private final String openingBracketRegex = "((\\()|(\\[)|(\\{)|(<)|(/\\*))";
private final String closingBracketRegex = "((\\))|(\\])|(\\})|(>)|(\\*/))";
private final Pattern openingBracketPattern = Pattern.compile(openingBracketRegex);
private final Pattern closingBracketPattern = Pattern.compile(closingBracketRegex);
private final Pattern BracketPattern = Pattern.compile(openingBracketRegex + "|" + closingBracketRegex);
@Override
@ -11,14 +22,19 @@ public class BracketServer implements CommandExecutor {
public boolean checkBrackets (String arg) {
Stack stack = new ListStack();
char[] chars = arg.toCharArray();
for (char x: chars) {
Character closingBracket = getClosingBracketForOpening(x);
StringBuilder builder = new StringBuilder(arg);
Matcher bracketMatcher = BracketPattern.matcher(builder.toString());
while (builder.toString().length() > 0 && bracketMatcher.find()) {
String foundString = bracketMatcher.group();
String closingBracket = getClosingBracketForOpening(foundString);
Matcher closingBracketMatcher = closingBracketPattern.matcher(foundString);
if(closingBracket != null){
stack.push(closingBracket);
} else if(isClosingBracket(x) && stack.pop() != (Character)x) {
} else if((closingBracketMatcher.matches()) && !foundString.equals(stack.pop())) {
return false;
}
builder = new StringBuilder(builder.substring(bracketMatcher.end()));
bracketMatcher = BracketPattern.matcher(builder.toString());
}
if(stack.isEmpty()){
return true;
@ -27,20 +43,20 @@ public class BracketServer implements CommandExecutor {
}
}
private Character getClosingBracketForOpening(char openingBracket) {
private String getClosingBracketForOpening(String openingBracket) {
switch (openingBracket){
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
case "(":
return ")";
case "[":
return "]";
case "{":
return "}";
case "<":
return ">";
case "/*":
return "*/";
}
return null;
}
private boolean isClosingBracket(char x) {
return x == ')' || x == ']' || x == '}';
}
}