如果给定字符串,递归地计算(不循环)的小写的“hi”的次数出现在字符串中给定一个字符串,递归地(没有循环)计算
countHi(“xxhixx”) - > 1
countHi( “xhixhixx”) - > 2
countHi( “HI”) - > 1
public class Tester {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int count = countHi("xxhixx");
System.out.println("countHi: " + count);
}
public static int countHi(String s) {
if (s.length() == 0) {
return 0;
}
int spot = s.indexOf("hi");
if(spot > 0)
{
String nextString = s.substring(spot + 2);
return 1 + countHi(nextString);
}
return 1;
}
}
而且你的问题是什么? –
'indexOf'使用循环。 –
问题是什么?我假设soem输入会返回一个太大的数字?您不会考虑大于0的字符串,但根本不包含“hi”。你的方法将返回1它shoudl返回0,您可以删除德支票长度== 0,而是区分(现货> = 0) - >递归调用+ 1和(现货< 0) ->返回0 –