Aufgabe 3 gelöst.

This commit is contained in:
schrom01 2022-09-20 20:48:39 +02:00
parent c035fd94ae
commit 09f62550d3
4 changed files with 54 additions and 7 deletions

View File

@ -47,5 +47,10 @@ public class ADS1_2_test {
public void testEmptyPop() {
assertNull(stack.pop());
}
@Test
public void testEmptyPeek() {
assertNull(stack.peek());
}
}

View File

@ -1,4 +1,4 @@
/*
package ch.zhaw.ads;
import org.junit.jupiter.api.BeforeEach;
@ -29,4 +29,3 @@ public class ADS1_3_test {
}
}
*/

View File

@ -0,0 +1,46 @@
package ch.zhaw.ads;
public class BracketServer implements CommandExecutor {
@Override
public String execute(String command) throws Exception {
return checkBrackets(command) ? "true" : "false";
}
public boolean checkBrackets(String command) {
Stack stack = new ListStack();
char[] chars = command.toCharArray();
for (char x: chars) {
Character closingBracket = getClosingBracketForOpening(x);
if(closingBracket != null){
stack.push(closingBracket);
} else if(isClosingBracket(x) && stack.pop() != (Character)x) {
return false;
}
}
if(stack.isEmpty()){
return true;
} else {
return false;
}
}
private Character getClosingBracketForOpening(char openingBracket) {
switch (openingBracket){
case '(':
return ')';
case '[':
return ']';
case '{':
return '}';
}
return null;
}
private boolean isClosingBracket(char x) {
return x == ')' || x == ']' || x == '}';
}
}

View File

@ -13,10 +13,7 @@ public class ListStack implements Stack {
@Override
public Object pop() {
if(arrayList.isEmpty()){
return null;
}
return arrayList.remove(0);
return arrayList.isEmpty() ? null : arrayList.remove(0);
}
@Override
@ -26,7 +23,7 @@ public class ListStack implements Stack {
@Override
public Object peek() {
return arrayList.get(0);
return arrayList.isEmpty() ? null : arrayList.get(0);
}
@Override