forked from zapellass123/OpenEmailGenerator
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BalancedParentheses.java
43 lines (36 loc) · 1.28 KB
/
BalancedParentheses.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
import java.util.Stack;
public class BalancedParentheses {
static boolean isBalanced(String input) {
Stack<Character> s = new Stack<>();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == '(' || ch == '[' || ch == '{') {
s.push(ch);
} else {
if (s.isEmpty())
return false;
char topCharacter = s.pop();
switch (ch) {
case ')':
if (topCharacter == '[' || topCharacter == '{') return false;
break;
case ']':
if (topCharacter == '(' || topCharacter == '{') return false;
break;
case '}':
if (topCharacter == '(' || topCharacter == '[') return false;
break;
}
}
}
return s.isEmpty();
}
public static void main(String[] args) {
String str = "([{}])";
if (isBalanced(str)) {
System.out.println("Input consists of Balanced Parentheses");
} else {
System.out.println("Input contains Unbalanced Parentheses");
}
}
}