Easy Problem: Transform the Expression

He’s an interesting albeit relatively easy problem from


Reverse Polish Notation (RPN) is a mathematical notation where every operator follows all of its operands. For instance, to add three and four, one would write “3 4 +” rather than “3 + 4”. If there are multiple operations, the operator is given immediately after its second operand; so the expression written “3 − 4 + 5” would be written “3 4 − 5 +” first subtract 4 from 3, then add 5 to that.

Transform the algebraic expression with brackets into RPN form.

You can assume that for the test cases below only single letters will be used, brackets [] will not be used and each expression has only one RPN form (no expressions like a*b*c)


The first line contains t, the number of test cases (less then 100).
Followed by t lines, containing an expression to be translated to RPN form, where the length of the expression is less then 400.


The expressions in RPN form, one per line.




My Solution

Most computer science students see this example in class while studying data structures, as you can solve this problem quite easily using a simple stack. You basically need to go through the original string, outputing letters as they come (since their order won’t change) and pushing operators into the stack. Then whenever you find a closing parentheses ‘)’ you pop and output everything on the stack until you find the matching opening parenthesis ‘(‘. I used Java because it already has a stack structure implemented (though implementing one is always fun and useful to polish your pointer skills).

import java.util.Stack;

public class Main{

  public static void main(String[] args){
    int i,j;
    j = 0;
    String x = "";

    BufferedReader br = new BufferedReader(new InputStreamReader(;
      j = Integer.parseInt(br.readLine());
    catch(IOException e){
        x = br.readLine();
      catch(IOException e){

  public static String rpn(String x){
    String result = "";
    char c = 'a';
    int i;
    Stack<Character> s = new Stack<Character>();
      c = x.charAt(i);
        result += c;
      else if(c==')'){
        while((c = s.pop())!='(')
          result += c;
    return result;


Leave a Reply

Your email address will not be published. Required fields are marked *