Java > Recursion-1 > pairStar (CodingBat Solution)

Problem:

Given a string, compute recursively a new string where identical chars that are adjacent in the original string are separated from each other by a "*".

pairStar("hello") → "hel*lo"
pairStar("xxyy") → "x*xy*y"
pairStar("aaaa") → "a*a*a*a"


Solution:

public String pairStar(String str) {
  if (str.equals("") || str.length() == 1) return str;
  if (str.charAt(0) == str.charAt(1)) 
    return str.charAt(0) + "*" + pairStar(str.substring(1));
  else
    return str.charAt(0) + pairStar(str.substring(1));
}


3 comments :

  1. public String pairStar(String str) {
       if(str.length() < 2)return str;
       return str.charAt(0)
                +(str.charAt(0)==str.charAt(1)?"*":"")
                +pairStar(str.substring(1));
    }

    ReplyDelete
  2. public String pairStar(String str) {
    if (str.length()<2)
    return str;

    String result = str.substring(0,1);
    if (str.charAt(0) == str.charAt(1))
    result += "*";

    return result + pairStar(str.substring(1));
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact