So, I was solving this problem on CodingBat
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"
Here is my code:
public String changePi(String str) {
if (str.length() < 2)
return str;
char c1 = str.charAt(0);
char c2 = str.charAt(1);
if (c1 == 'p' && c2 == 'i')
return "3.14" + changePi(str.substring(2));
return c1 + c2 + changePi(str.substring(2));
}
This code is not working for many test cases as shown in the image below
I'm unable to understand what is wrong with my recursive code and why it is showing such output. Can anyone please help me in understanding what I did wrong?