-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBracketsChecker.java
More file actions
52 lines (44 loc) · 1.22 KB
/
BracketsChecker.java
File metadata and controls
52 lines (44 loc) · 1.22 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
/**
* Algorithm to check if a string has correct brackets.
*/
package misc;
import linkedlist.LinkedList;
import java.util.Arrays;
class BracketsChecker {
// Open brackets symbols.
static String OPEN = "{[(";
// Closed brackets symbols in same order.
static String CLOSED = "}])";
/**
* Checks the algorithm for a set of strings.
* @param args Arguments of the program. Unused.
*/
public static void main(String[] args) {
String[] codes = {"asdasd([asdasad])[", "({[]})", "({[}])"};
for (String code : codes) {
System.out.println(code + " : " + isValid(code));
}
}
/**
* Checks if the code is valid by adding all items to the stack.
* @param code String to check.
* @return True - if the code valid, False - if it's not.
*/
public static boolean isValid(String code) {
LinkedList<Integer> s = new LinkedList<Integer>();
for (char c : code.toCharArray()) {
int bracketType = OPEN.indexOf(c);
if (bracketType != -1) {
s.push(bracketType);
}
bracketType = CLOSED.indexOf(c);
if (bracketType != -1) {
if (s.value != bracketType) {
return false;
}
s.pop();
}
}
return s.size == 0;
}
}