Wednesday, May 7, 2014

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"


public static String pairStar(String str) {
String result = "";
if (str == null) {
return result;
}
result = str.substring(0, 1);

if (str.trim().length() == 1)
return result;

if (result.equals(str.substring(1, 2))) {
result += "*";
}

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

}


ex : hello

 - checks whether  "h".equals("e")
 - if No
        - "h" will be added to the result
        - pairStar() is invoked again with the string "ello".

   [In program, it can be mapped like return "h"+pairStar("ello");]

  - checks whether  "e".equals("l")
  - if No
        - "e" will be added to the result
        - pairStar() is invoked again with the string "llo".
 - checks whether  "l".equals("l")
  - if Yes
        - "l" will be added to the result with a "*" after it.
        - pairStar() is invoked again with the string "lo".
  - checks whether  "l".equals("o")
  - if No
        - "l" will be added to the result.
        - pairStar() is invoked again with the string "o".
  - checks whether  string "o" has one character
  - if Yes
        - return o;
        - result will now have hel*l with the o appended at the last

So the output will be "hel*lo";


No comments:

Post a Comment