Java > Recursion-1 > changeXY (CodingBat Solution)

Problem:

Given a string, compute recursively (no loops) a new string where all the lowercase 'x' chars have been changed to 'y' chars.

changeXY("codex") → "codey"
changeXY("xxhixx") → "yyhiyy"
changeXY("xhixhix") → "yhiyhiy"


Solution:

public String changeXY(String str) {
  if (str.equals("")) return str;
  if (str.charAt(0) == 'x') return "y" + changeXY(str.substring(1));
  return str.charAt(0) + changeXY(str.substring(1));
}


4 comments :

  1. public String changeXY(String str) {
    int idx = str.indexOf("x");

    if (idx==-1)
    return str;

    if (idx==0)
    return changeXY("y"+str.substring(1));
    else if (idx==str.length()-1)
    return changeXY(str.substring(0, str.length()-1)+"y");
    else{
    return changeXY(str.substring(0, idx)+"y"+str.substring(idx+1, str.length()));
    }

    }

    ReplyDelete
  2. public String changePi(String str) {
    int idx = str.indexOf("pi");
    if (idx==-1)
    return str;

    return changePi(str.substring(0,idx)+"3.14"+str.substring(idx+2));
    }

    ReplyDelete
  3. public String changeXY(String str) {
    return str.replace('x','y');
    }

    ReplyDelete
  4. public boolean array6(int[] nums, int index) {
    if (nums.length == 0 || index == nums.length)
    return false;
    return nums[index] == 6 || array6(nums, index + 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