Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

9) Write a recursive function (static method) called parenCleaner that takes a S

ID: 3844225 • Letter: 9

Question

9)   Write a recursive function (static method) called parenCleaner that takes a String as a parameter, and returns a new String where all of the open parentheses (i.e. ‘(‘) have been moved to the beginning of the String and all of the closed parens (i.e. ‘)’) have been moved to the end of the String. This example question may help with this question (this is probably easier than you think). For example:

parenCleaner(“x()y()z(a)”) => “(((xyza)))”

parenCleaner(“f(x,y,z)”) => “(fx,y,z)”

parenCleaner(“pumpkins”) => “pumpkins”


public static String parenCleaner(String str) {

Explanation / Answer

public static String parenCleaner(String str)

   {

       String s="";

       String end="";

       for(int i=0;i<str.length();i++)

       {

           if(str.charAt(i)=='(')

           {

               s = '('+s;

           }

           else if(str.charAt(i)==')')

           {

               end = end+')';

           }

           else

           {

               s = s+str.charAt(i);

           }

       }

       return s+end;

   }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote