Skip to content

Commit

Permalink
Brackets
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianiacobghiula committed Jun 7, 2020
1 parent 5b89135 commit 793ecc2
Show file tree
Hide file tree
Showing 2 changed files with 82 additions and 0 deletions.
50 changes: 50 additions & 0 deletions src/main/java/codility/p07_stacks_and_queues/Brackets.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package codility.p07_stacks_and_queues;

import java.util.ArrayDeque;
import java.util.Deque;

/*
https://app.codility.com/programmers/lessons/7-stacks_and_queues/brackets/
*/
public class Brackets {

public static final int INVALID_NESTING = 0;
public static final int PROPERLY_NESTING = 1;

private boolean isProperlyNested(char current, char popped) {
return ((popped == '(') && (current == ')')) ||
((popped == '[') && (current == ']')) ||
((popped == '{') && (current == '}'));
}

//https://app.codility.com/demo/results/training6VUEYT-SDD/
public int solution(String S) {
Deque<Character> stack = new ArrayDeque<Character>();
for (Character value : S.toCharArray()) {
switch (value) {
case '(':
case '[':
case '{': {
stack.push(value);
break;
}
case ')':
case ']':
case '}': {
if (stack.isEmpty()) {
return INVALID_NESTING;
}
Character popped = stack.pop();
if (!isProperlyNested(value, popped)) {
return INVALID_NESTING;
}
}

}
}
if (!stack.isEmpty()) {
return INVALID_NESTING;
}
return PROPERLY_NESTING;
}
}
32 changes: 32 additions & 0 deletions src/test/java/codility/p07_stacks_and_queues/BracketsTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package codility.p07_stacks_and_queues;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static codility.p07_stacks_and_queues.Brackets.PROPERLY_NESTING;
import static codility.p07_stacks_and_queues.Brackets.INVALID_NESTING;
import static org.assertj.core.api.Assertions.assertThat;

public class BracketsTest {

Brackets brackets;

@BeforeEach
public void init() {
brackets = new Brackets();
}

@Test
public void sample1() {
int solution = brackets.solution("{[()()]}");
assertThat(solution).isEqualTo(PROPERLY_NESTING);
}

@Test
public void sample2() {
int solution = brackets.solution("([)()]");
assertThat(solution).isEqualTo(INVALID_NESTING);
}


}

0 comments on commit 793ecc2

Please sign in to comment.