-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParenthesisChecker.java
More file actions
52 lines (45 loc) · 1.47 KB
/
ParenthesisChecker.java
File metadata and controls
52 lines (45 loc) · 1.47 KB
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
/***
<Allan Villegas Jr.>
DataStruct 21 - 06973
Parenthesis Checker
- a program that will the correct pairing of parenthesis
<>[](){}
**/
import java.io.File;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class ParenthesisChecker{
public static boolean isBalance(String str){
String closings = ">}])";
MyStackLinked myStack = new MyStackLinked();
for(int i = 0; i < str.length(); i++){
char ch = str.charAt(i);
if(closings.indexOf(ch) != -1) {
if(i==0 || !isPair(myStack.peek(), ch))
return false;
myStack.pop();
}else
myStack.push(ch);
}
return myStack.isEmpty();
}
public static boolean isPair(Object x, Object y) {
String openings = "<>(){}[]";
if(x == null)
return false;
String pair = x.toString() + y.toString();
return openings.contains(pair);
}
static public void main(String ...args){
try {
Scanner reader = new Scanner(new File("file.txt"));
while(reader.hasNextLine()){
String str = reader.nextLine().trim();
if(str != "")
System.out.printf("%s -> %s\n",str,isBalance(str) ? "Balanced" : "UnBalanced");
}
}catch(FileNotFoundException e){
System.out.print("File not Found");
}
} // end of main method
} // end of class