Problem:
Given a string, compute recursively (no loops) a new string where all appearances of "pi" have been replaced by "3.14".
changePi("xpix") → "x3.14x"
changePi("pipi") → "3.143.14"
changePi("pip") → "3.14p"
Solution:
public String changePi(String str) { if (str.equals("") || str.length() < 2) return str; if (str.charAt(0) == 'p' && str.charAt(1) == 'i') return "3.14" + changePi(str.substring(2)); return str.charAt(0) + changePi(str.substring(1)); }
if (str.equals("") || str.length() < 2) return str;
ReplyDeleteit should be:
if (str.equals("") || str.length() < 2) return newStr+str;
No, it should be
Deleteif(str.length() < 2) return str;
public String changePi(String str) {
ReplyDeleteif(str.length() < 2) return str;
if(str.substring(0, 2).equals("pi")) return "3.14" + changePi(str.substring(2));
return str.charAt(0) + changePi(str.substring(1));
Thanks a lot searching for this.
ReplyDeletepublic 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 changePi(String str) {
ReplyDeleteif(str.equals(""))
return str;
else if(str.startsWith("pi"))
return "3.14"+changePi(str.substring(2));
else return str.charAt(0)+changePi(str.substring(1));
}