File tree Expand file tree Collapse file tree 2 files changed +102
-0
lines changed
Basics/Data Structure/Stack-Paranthesizer Expand file tree Collapse file tree 2 files changed +102
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments