-
Notifications
You must be signed in to change notification settings - Fork 13
/
Stack_ParenthesisChecker.java
92 lines (85 loc) · 2.27 KB
/
Stack_ParenthesisChecker.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
// https://practice.geeksforgeeks.org/problems/parenthesis-checker/0
// https://leetcode.com/problems/valid-parentheses/discuss/9178/Short-java-solution
class Stack_ParenthesisChecker {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-->0) {
String ip = br.readLine().trim();
System.out.println(parenthesisChecker(ip) ? "balanced" : "not balanced");
}
}
private static boolean parenthesisChecker(String s) {
if(s.length() % 2 != 0) return false; // return false if the string has an odd length
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()) {
if(c == '(')
stack.push(')');
else if(c == '{')
stack.push('}');
else if(c == '[')
stack.push(']');
else if(stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}
// OLD SOLUTION
/*
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-->0)
{
String s = br.readLine();
if(areParenthesisBalanced(s))
{
System.out.println("balanced");
}
else
{
System.out.println("not balanced");
}
}
}
static boolean areParenthesisBalanced(String s)
{
Stack<Character> input = new Stack<>();
for (int i = 0; i < s.length(); i++)
{
if(s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{')
{
input.push(s.charAt(i));
}
else if(s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)=='}')
{
if(input.isEmpty()) {
return false;
}
else if ( !isMatchingPair((char)input.pop(), s.charAt(i)) )
{
return false;
}
}
}
if(input.isEmpty()) return true;
else return false;
}
static boolean isMatchingPair(char character1, char character2)
{
if (character1 == '(' && character2 == ')')
return true;
else if (character1 == '{' && character2 == '}')
return true;
else if (character1 == '[' && character2 == ']')
return true;
else
return false;
}
*/
}