【发布时间】:2011-11-14 15:40:29
【问题描述】:
首先,这不是家庭作业。只有我在练习。 我试图递归地确定“hi”出现在给定字符串中的次数,但在每种情况下,它都会跳到最后一个 else if 语句并且字符串为空。有什么想法吗?
基本上, if(字符串以“hi”开头) 将 count 加 1 并在第二个索引之后使用字符串递归以跳过它刚刚计数的“hi”
else if(字符串不以“hi”开头且字符串不为空) 递归第一个索引后的字符串,以查看下一次它是否以“hi”开头。
else if(字符串为空) Print("到达文本结尾") 返回计数;
public class Practice {
public int recur(String str, int counter){
int count=counter;
if(str.startsWith("hi")){
count++;
recur(str.substring(2),count);
}
else if((!str.isEmpty())&&(!str.startsWith("hi"))){
recur(str.substring(1),count);
}
else if(str.isEmpty()){
System.out.println("End of text reached");
return count;
}
return count;
}
public static void main(String args[]){
String str="xxhixhixx";
Practice p=new Practice();
System.out.println(p.recur(str, 0));
}
}
【问题讨论】:
-
相比字符串处理wiki,在递归实践中确实有更好的例子。
-
我对此有疑问 - 任何调用者都可以修改结果,因为
counter是外部调用的一部分。至少,这应该是private,使用public包装器不 包含counter(并且不是递归的)。另一种方法是在递归返回期间进行加法。此外,您正在检查startsWith,然后将光标移动 1 -indexOf有什么问题(我认为那里有更好的优化)。