forked from oleg-cherednik/DailyCodingProblem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
41 lines (33 loc) · 1.05 KB
/
Solution.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
import java.util.Deque;
import java.util.LinkedList;
/**
* @author Oleg Cherednik
* @since 01.02.2018
*/
public class Solution {
public static void main(String... args) {
System.out.println(isBalanced("([])[]({})")); // true
System.out.println(isBalanced("([)]")); // false
System.out.println(isBalanced("((()")); // false
}
public static boolean isBalanced(String str) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(ch);
else {
if (stack.isEmpty())
return false;
char prv = stack.pop();
if (prv == '(' && ch != ')')
return false;
if (prv == '[' && ch != ']')
return false;
if (prv == '{' && ch != '}')
return false;
}
}
return stack.isEmpty();
}
}