-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
115 lines (86 loc) · 2.72 KB
/
Solution.java
File metadata and controls
115 lines (86 loc) · 2.72 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package string.braces;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
/**
* Braces Validator
*/
class Solution {
private final Map<Character, Character> startEndDefs;
public Solution() {
startEndDefs = Map.of(//@formatter:off
'[', ']',
'(', ')',
'{', '}'
);//@formatter:on
}
public boolean isBrace(char value) {
return value == '[' || value == ']' || value == '(' || value == ')' || value == '{' || value == '}';
}
public Result validate(String value) {
Deque<Brace> opened = new ArrayDeque<>();
Result result = new Result(value);
for (int i = 0; i < value.length(); i++) {
char character = value.charAt(i);
if (!isBrace(character)) {
continue;
}
Brace brace = new Brace(character, i);
if (startEndDefs.containsKey(brace.value)) {
opened.push(brace);
continue;
}
if (opened.isEmpty()) {
result.setBraceInError(brace);
break;
}
Brace lastOpenBrace = opened.pop();
char expectedCloseBrace = startEndDefs.get(lastOpenBrace.value);
if (brace.value != expectedCloseBrace) {
result.setBraceInError(brace);
break;
}
}
if (result.isValid() && !opened.isEmpty()) {
result.setBraceInError(opened.pop());
}
return result;
}
public static class Brace {
public char value;
public int index;
public Brace(char value, int index) {
this.value = value;
this.index = index;
}
}
public static class Result {
private boolean valid;
private Brace braceInError;
private String value;
public Result(String value) {
this.valid = true;
this.value = value;
}
public void setBraceInError(Brace brace) {
this.braceInError = brace;
this.valid = false;
}
public boolean isValid() {
return valid;
}
public Brace getBraceInError() {
return braceInError;
}
public String getValue() {
return value;
}
public String getValidMessage() {
return valid ? "YES" : string.braces.Solution.Result.getErrorMessage(value, braceInError);
}
public static String getErrorMessage(String value, Brace brace) {
String pad = " ".repeat(Math.max(0, brace.index));
return value + System.lineSeparator() + pad + "^ ERROR: brace " + brace.value + " is not closed";
}
}
}