-
Notifications
You must be signed in to change notification settings - Fork 1
/
ValidBraces.java
35 lines (30 loc) · 1.09 KB
/
ValidBraces.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package katas.java;
import java.util.Map;
import java.util.Stack;
/**
* @author JDev
* <p>
* Kata: https://www.codewars.com/kata/5539fecef69c483c5a000015
*/
public class ValidBraces {
public static void main(String[] args) {
System.out.println(isValid("( ) {}[]")); // => True
System.out.println(isValid("([{}])")); // => True
System.out.println(isValid("(}")); // => False
System.out.println(isValid("[(])")); // => False
System.out.println(isValid("[({})](]")); // => False
System.out.println(isValid("((({")); // => False
}
private static boolean isValid(String braces) {
Stack<Character> bStack = new Stack<Character>();
Map<Character, Character> pairs = Map.of('[', ']', '{', '}', '(', ')');
for (char c : braces.replaceAll("\\s", "").toCharArray()) {
if (String.valueOf(c).matches("[\\[\\{\\(]")) {
bStack.push(c);
} else if (bStack.isEmpty() || pairs.get(bStack.pop()) != c) {
return false;
}
}
return bStack.isEmpty();
}
}