Aufgabe 3 gelöst.
This commit is contained in:
parent
c035fd94ae
commit
09f62550d3
|
@ -47,5 +47,10 @@ public class ADS1_2_test {
|
|||
public void testEmptyPop() {
|
||||
assertNull(stack.pop());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEmptyPeek() {
|
||||
assertNull(stack.peek());
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
/*
|
||||
|
||||
package ch.zhaw.ads;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
|
@ -29,4 +29,3 @@ public class ADS1_3_test {
|
|||
}
|
||||
}
|
||||
|
||||
*/
|
|
@ -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 == '}';
|
||||
}
|
||||
|
||||
}
|
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue