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: //new Tests:
test("(",false); test("(",false);
test(")",false); test(")",false);
test("<(<>)>",true);
test("<(<)>>",false);
} }
} }

View File

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