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 ;
}
}