【发布时间】:2015-03-27 01:04:34
【问题描述】:
我需要编写一个名为 indexOf 的递归方法,它接受两个字符串作为参数,并返回第一个字符串中第二个字符串第一次出现的起始索引(如果未找到,则返回 -1)。我必须使用递归来解决这个问题。 以下是一些示例结果:
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
这是我的解决方案,但它给了我 6 的 indexOf("Barack Obama", "McCain") 而不是 -1。
public static int indexOf(String s1, String s2) {
if(s1.equals(s2))
return 0;
else
return indexOfHelper(s1, s2, 0);
}
private static int indexOfHelper(String s1, String s2, int ctr) {
if(s2.length() > s1.length())
return -1;
if(s2.length() == 0 || s1.length() == 0) //base case
return ctr;
else //recursive case
if(s1.charAt(0) == s2.charAt(0)){ //if there is a matching character
if(s1.substring(0, s2.length()).equals(s2))
return ctr; //if there is a matching character and the rest of the strings match as well
else
return -1; //if there is a matching character but the rest of the strings don't match
}
else
return 1 + indexOfHelper(s1.substring(1), s2, ctr);
}
【问题讨论】:
-
你说“它不起作用”是什么意思?怎么不行?
-
如果寻找匹配的 starting 索引,为什么代码“1 +”(递归)索引?慢慢地逐步完成程序(使用调试器和/或手动)并验证有关它的值和假设。
-
例如:indexOf("Barak obama", "ck") 给我答案 5 而不是 4
标签: java