编写一个递归方法indexOf,它接受两个字符串作为参数,并返回第一个字符串中第二个字符串第一次出现的起始索引(如果未找到,则返回-1)。下表列出了对您的方法的多次调用及其预期返回值。请注意,大小写很重要,如最后一个返回 -1 的示例。
Call Value Returned
indexOf("Barack Obama", "Bar") 0
indexOf("Barack Obama", "ck") 4
indexOf("Barack Obama", "a") 1
indexOf("Barack Obama", "McCain") -1
indexOf("Barack Obama", "BAR") -1
字符串有一个indexOf方法,但不允许调用它。您仅限于以下方法:
方法说明
equals(String other) //returns true if the two Strings contain the same characters
length() //returns the int number of characters in the String
substring(int fromIndex, int toIndex)
substring(int fromIndex) //returns a new String containing the characters from this
//String from fromIndex (inclusive) to toIndex (exclusive),
//or to the end of the String if toIndex is omitted
不允许构造除字符串之外的任何结构化对象(不允许数组、List、Scanner 等),并且不能使用任何循环来解决此问题;您必须使用递归。
public int indexOf(String s, String b){
if(s.length() <= b.length() && !s.equals(b)){return -1;}
if(s.substring(0, b.length()).equals(b)){return 0;}
return 1 + indexOf(s.substring(b.length()), b);
}
最佳答案
为了让 FreddyDs 的答案起作用,需要进行两个细微的更改:
public static int indexOf(String s, String b){
if(s.length() <= b.length() && !s.equals(b)){return -1;}
if(s.substring(0, b.length()).equals(b)){return 0;}
int result = indexOf(s.substring(1, s.length()), b);
return result == -1 ? -1 : 1 + result;
}
关于java - 我不知道我在这个java递归问题上做错了什么!我在下面发布了练习和我的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62141481/