diff --git a/src/ch/zhaw/ads/ADS1_3_test.java b/src/ch/zhaw/ads/ADS1_3_test.java index f35fd0d..f2b7e5a 100644 --- a/src/ch/zhaw/ads/ADS1_3_test.java +++ b/src/ch/zhaw/ads/ADS1_3_test.java @@ -32,5 +32,8 @@ public class ADS1_3_test { //new Tests: test("(",false); test(")",false); + + test("<(<>)>",true); + test("<(<)>>",false); } } diff --git a/src/ch/zhaw/ads/BracketServer.java b/src/ch/zhaw/ads/BracketServer.java index 9cc6607..c41d31b 100644 --- a/src/ch/zhaw/ads/BracketServer.java +++ b/src/ch/zhaw/ads/BracketServer.java @@ -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 == '}'; - } - } \ No newline at end of file