Skip to main content
  1. Problem Solving Solutions/

Given a string "3(ab)4(cd)" expand it into "abababcdcdcdcd"

·1 min read
Problem Solving
Mayukh Datta
Author
Mayukh Datta

This problem was asked in ThoughtWorks interview held in October 2018. Given a string “3(ab)4(cd)”, we have to write a program to expand it into “abababcdcdcdcd”.

Java code:

import java.io.*; public class expand{ public static void main(String args[]) throws IOException{ String strin, temp; int j; temp = “”; //initialize to null

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter a string: ");
    strin = in.readLine();

    for(int i=0;i<strin.length();i++){
        if(strin.charAt(i) >= 0){
            int num = strin.charAt(i) - '0'; //subtract 0 to convert char into int
            if(strin.charAt(i+1) == '('){
                //within brackets
                for(j=i+1;strin.charAt(j)!=')';j++){
                    if((strin.charAt(j) >= 'a' && strin.charAt(j) <= 'z') || (strin.charAt(j) >= 'A' && strin.charAt(j) <= 'Z')){
                        temp = temp.concat(Character.toString(strin.charAt(j)));
                    }
                }
                //expanding
                for(int k=1;k<=num;k++){
                    System.out.print(temp);
                }
                //reset
                num=0;
                temp="";
                if(j<strin.length()){ //to prevent array access out of its bounds
                    i = j;
                }
            }
        }
    }
    System.out.println("");
}

}