Skip to content

Commit 77030df

Browse files
Paranthesizer using stack
1 parent 5652731 commit 77030df

File tree

2 files changed

+102
-0
lines changed

2 files changed

+102
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package Stack;
2+
3+
import java.util.Scanner;
4+
5+
public class Paranthesizer {
6+
static String expr;
7+
public static void main(String[] args) {
8+
Scanner sc = new Scanner(System.in);
9+
System.out.println("Enter your expression : ");
10+
expr = sc.nextLine();
11+
boolean res = checker();
12+
System.out.println(res?"Valid Expression":"Invalid Expression");
13+
sc.close();
14+
}
15+
16+
public static int countParanthesis(){
17+
int count = 0;
18+
for (int i = 0; i < expr.length(); i++) {
19+
if (expr.charAt(i) == '(' || expr.charAt(i) == '{' || expr.charAt(i) == '[') {
20+
count++;
21+
}
22+
}
23+
24+
return count;
25+
}
26+
27+
public static boolean checker(){
28+
StackX stk = new StackX(countParanthesis());
29+
30+
for (char element : expr.toCharArray()) {
31+
if(element == '(' || element == '{' || element == '['){
32+
stk.push(element);
33+
}
34+
35+
if (element == ')' && stk.peek() == '(') {
36+
stk.pop();
37+
}else if (element == '}' && stk.peek() == '{') {
38+
stk.pop();
39+
}else if (element == ']' && stk.peek() == '[') {
40+
stk.pop();
41+
}
42+
}
43+
44+
return stk.isEmpty();
45+
}
46+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package Stack;
2+
3+
public class StackX {
4+
private char[] data; //stack array
5+
private int top; //top of the stack
6+
private int size; //size of stack array
7+
8+
public StackX(int size){
9+
this.size = size;
10+
data = new char[size];
11+
top = -1;
12+
}
13+
14+
//push method
15+
public boolean push(char element){
16+
if (top < size - 1) {
17+
data[++top] = element;
18+
return true;
19+
}
20+
21+
return false;
22+
23+
}
24+
25+
public char pop(){
26+
if (top != -1) {
27+
return data[top--];
28+
}
29+
30+
return ' ';
31+
}
32+
33+
public char peek(){
34+
if (top != -1) {
35+
return data[top];
36+
}
37+
38+
return ' ';
39+
}
40+
41+
public boolean isFull(){
42+
if (top == size - 1) {
43+
return true;
44+
}
45+
46+
return false;
47+
}
48+
49+
public boolean isEmpty(){
50+
if (top == -1) {
51+
return true;
52+
}
53+
54+
return false;
55+
}
56+
}

0 commit comments

Comments
 (0)