-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBracketMatch.java
More file actions
54 lines (45 loc) · 1.3 KB
/
BracketMatch.java
File metadata and controls
54 lines (45 loc) · 1.3 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
package CodeChallenges;
import java.util.Stack;
public class BracketMatch {
public static void main(String[] args) {
System.out.println(bracketMatch("(()")); // Should be one
System.out.println(bracketMatch("(())")); // 0
System.out.println(bracketMatch("())(")); // 2
System.out.println(bracketMatch("())())()))")); // 4
System.out.println(bracketMatch(""));
System.out.println();
System.out.println(bracketMatchWOStack("(()")); // 1
System.out.println(bracketMatchWOStack("(())")); // 0
System.out.println(bracketMatchWOStack("())(")); // 2
System.out.println(bracketMatchWOStack("())())()))")); // 4
}
static int bracketMatch(String s) {
Stack<Character> bracketList = new Stack<>();
for(int i = 0; i < s.length(); i++) {
if(!bracketList.isEmpty() &&
bracketList.contains('(') &&
s.charAt(i) == ')') bracketList.remove(bracketList.lastIndexOf('('));
else bracketList.push((s.charAt(i)));
}
return bracketList.size();
}
static int bracketMatchWOStack(String s) {
int brackets = 0;
int left = 0;
for(int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
brackets++;
}
else {
//pop if there is a left bracket
if(left > 0) {
left--;
brackets--;
}
else brackets++;
}
}
return brackets;
}
}