【发布时间】:2020-08-13 12:28:41
【问题描述】:
我已经在这里和其他地方阅读了许多以前的问题,但我还没有找到我需要的东西。 我需要编写 indexOf 的递归实现。问题是我不能使用任何局部变量,而只能输入一个字符串和一个字符。
该方法应该返回一个介于 0 和字符串长度之间的值 - 如果找到了 char,则返回 1,如果不存在,则返回 -1。 我知道实际的“indexOf”也允许您搜索字符串,但这种方法被简化了。
我试过这个,但它很愚蠢,因为我使用了真正的 indexOf:
public static int indexOf(String s, char c){
if(s.indexOf(c) < 0){ // I'd like to change this
return -1;
}
if (s.length() == 0) //base case #1
{
return -1;
}
else if (s.charAt(0) == c) //base case #2
{
return 0;
}
else {
return 1 + indexOf(s.substring(1), c);
}
}
我特别看到了this,但是没有变量可以写吗?谢谢
【问题讨论】: