forked from anitaa1990/Android-Cheat-sheet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEqualDelimiters.java
55 lines (37 loc) · 1.17 KB
/
EqualDelimiters.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package stacks;
import java.util.Stack;
public class EqualDelimiters {
public static boolean checkIfDelimiterIsEqual(String s) {
char[] charArr = s.toCharArray();
if(charArr.length <= 1) return true;
Stack<Character> stack = new Stack<>();
for(Character c : charArr) {
if(c == '[' || c == '{' || c == '(') {
stack.push(c);
}
if(c == ')' || c == ']' || c == '}') {
if (stack.isEmpty()) {
return false;
}
Character character = stack.peek();
if (c == ')' && character == '(') {
stack.pop();
}
if (c == ']' && character == '[') {
stack.pop();
}
if (c == '}' && character == '{') {
stack.pop();
}
}
}
if(s.length() > 0 && stack.isEmpty()){
return true;
}
return false;
}
public static void main(String[] args) {
String string = "{[]}";
System.out.println(checkIfDelimiterIsEqual(string));
}
}