Resolves Java Stack task
This commit is contained in:
parent
880f1b2d2c
commit
6e357de888
2 changed files with 108 additions and 0 deletions
|
@ -0,0 +1,41 @@
|
|||
package eu.ztsh.training.hackerrank.datastructures.stack;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Scanner;
|
||||
import java.util.Stack;
|
||||
|
||||
/**
|
||||
* Java Stack task.
|
||||
* source: https://www.hackerrank.com/challenges/java-stack
|
||||
*/
|
||||
public class Solution {
|
||||
|
||||
public static void main(String[] args) {
|
||||
var scanner = new Scanner(System.in);
|
||||
while (scanner.hasNext()) {
|
||||
var stack = new Stack<Character>();
|
||||
var line = scanner.next();
|
||||
for (char input : line.toCharArray()) {
|
||||
if (stack.empty()) {
|
||||
stack.push(input);
|
||||
continue;
|
||||
}
|
||||
char head = stack.peek();
|
||||
if (closingChars.getOrDefault(input, '0').equals(head)) {
|
||||
stack.pop();
|
||||
} else {
|
||||
stack.push(input);
|
||||
}
|
||||
}
|
||||
System.out.println(stack.empty());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private static final Map<Character, Character> closingChars = Map.of(
|
||||
']', '[',
|
||||
'}', '{',
|
||||
')', '('
|
||||
);
|
||||
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
package eu.ztsh.training.hackerrank.datastructures.stack;
|
||||
|
||||
import java.util.List;
|
||||
import eu.ztsh.training.hackerrank.HackerRankTest;
|
||||
import eu.ztsh.training.hackerrank.SolutionClassDescription;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
@DisplayName("HackerRank challenges: Java Stack")
|
||||
class SolutionTest extends HackerRankTest {
|
||||
|
||||
@Test
|
||||
public void testCase0() {
|
||||
simpleAssert(
|
||||
List.of(
|
||||
"{}()",
|
||||
"({()})",
|
||||
"{}(",
|
||||
"[]"
|
||||
),
|
||||
List.of(
|
||||
"true",
|
||||
"true",
|
||||
"false",
|
||||
"true"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCase1() {
|
||||
simpleAssert(
|
||||
List.of(
|
||||
"({}[])",
|
||||
"(({()})))",
|
||||
"({(){}()})()({(){}()})(){()}",
|
||||
"{}()))(()()({}}{}",
|
||||
"}}}}",
|
||||
"))))",
|
||||
"{{{",
|
||||
"(((",
|
||||
"[]{}(){()}((())){{{}}}{()()}{{}{}}",
|
||||
"[[]][][]",
|
||||
"}{"
|
||||
),
|
||||
List.of(
|
||||
"true",
|
||||
"false",
|
||||
"true",
|
||||
"false",
|
||||
"false",
|
||||
"false",
|
||||
"false",
|
||||
"false",
|
||||
"true",
|
||||
"true",
|
||||
"false"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected SolutionClassDescription getSolutionClassDescription() {
|
||||
return new SolutionClassDescription(Solution.class);
|
||||
}
|
||||
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue