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)); }
public String changeXY(String str) {
ReplyDeleteint 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()));
}
}
public String changePi(String str) {
ReplyDeleteint idx = str.indexOf("pi");
if (idx==-1)
return str;
return changePi(str.substring(0,idx)+"3.14"+str.substring(idx+2));
}
public String changeXY(String str) {
ReplyDeletereturn str.replace('x','y');
}
public boolean array6(int[] nums, int index) {
ReplyDeleteif (nums.length == 0 || index == nums.length)
return false;
return nums[index] == 6 || array6(nums, index + 1);
}