-
Notifications
You must be signed in to change notification settings - Fork 20
/
lab2_solution.java
67 lines (51 loc) · 1.39 KB
/
lab2_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
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
// Lab 2 Solution
import java.util.*;
import java.util.Scanner;
/*********************************************************************/
// Write your code here
class Parser {
public Parser() {}
private boolean isOpen(char c) {
return (c == '(' || c == '{');
}
private boolean isClose(char c) {
return (c == ')' || c == '}');
}
private boolean isMatch(char a, char z) {
if (a == '{' && z == '}')
return true;
if (a == '(' && z == ')')
return true;
return false;
}
public boolean checkParenthesesBalance(String str) {
Stack s = new Stack();
for(char c: str.toCharArray()) {
if( isOpen(c) ) {
s.push(c);
} else if( isClose(c)) {
if (s.empty())
return false;
char t = (char)s.pop();
if (!isMatch(t,c))
return false;
}
}
if(s.empty())
return true;
else
return false;
}
}
// Write your solution above
/*********************************************************************/
class Solution{
public static void main(String []argh)
{
Parser X=new Parser();
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(X.checkParenthesesBalance(in.next()));
}
}
}