-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathBalanced_Parenthesis.java
55 lines (51 loc) · 1.57 KB
/
Balanced_Parenthesis.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
public class Balanced_Parenthesis {
public static void main(String[] args) {
String parenthesis = "}{";
int res = balanced_Parenthesis(parenthesis);
System.out.println(res);
}
public static int balanced_Parenthesis(String inputStr) {
int i, length, j = 0, count = 0;
int counter = 0;
char current, ch;
char[] stack = new char[20];
length = inputStr.length();
for (i = 0; i < length; i++) {
current = inputStr.charAt(i);
if (current == '(' || current == '{' || current == '[') {
stack[j] = current;
j++;
count = 1;
counter++;
} else if (current == ')') {
if (count == 1) {
j--;
counter--;
}
ch = stack[j];
if (stack.length == 0 || ch != '(') {
counter++;
}
} else if (current == '}') {
if (count == 1) {
j--;
counter--;
}
ch = stack[j];
if (stack.length == 0 || ch != '{') {
counter++;
}
} else if (current == ']') {
if (count == 1) {
j--;
counter--;
}
ch = stack[j];
if (stack.length == 0 || ch != '[') {
counter++;
}
}
}
return counter;
}
}