https://www.codechef.com/LRNDSA02/problems/INPSTFIX

I have used stack here and I have tried debugging as well as including empty string also but it is not working any way.
/* package codechef; // don’t place package name! */

import java.util.;
import java.lang.
;
import java.io.*;

/* Name of the class has to be “Main” only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in) ;
int t = sc.nextInt() ;
while(t-- > 0){
int n = sc.nextInt() ;
String str = sc.next() ;
String res = “” ;
Stack st = new Stack<>() ;

    for(int i = 0 ; i < n ; i++){

        if(str.charAt(i) >= 'A' && str.charAt(i) <= 'Z'){
        res += str.charAt(i) ;

        }
        
        else if(str.charAt(i) == '('){
        st.push(str.charAt(i));

        }
        
        else if(str.charAt(i) == ')'){
            
        while(!st.isEmpty() && st.peek() != '('){
            res += st.peek() ;
            st.pop() ;
        }
        if(!st.isEmpty()){
            st.pop() ;
        }
        
    }
        
        else{
           while(!st.isEmpty() && prec(st.peek()) > prec(str.charAt(i))){
           res += st.peek() ;
           st.pop() ;
           }
           st.push(str.charAt(i));
        }

    }
    while(!st.isEmpty()){
        res += st.peek() ;
        st.pop();
    }
    System.out.println(res);
}

}
public static int prec(char i){
    if(i == '^')
    return 3 ;
    
    else if(i == '*' || i == '/')
    return 2 ;
    
    else if(i == '+' || i == '-')
    return 1 ;
    
    else
    return -1 ;
}

}

Your answer for:

1
19
E-(B-(C*D^A)+(F*G))

doesn’t look right.

Edit:

Smaller:

1
11
A^B-B+F/(C)

can u guide me plz where I am wrong I have drained my brain on this but i can’t find or should I think of another approach

This bit’s wrong.

Thanx it should have been >= instead of > :slight_smile: Thanx for ur help bruu

1 Like