【发布时间】:2018-01-27 15:06:37
【问题描述】:
我正在努力解决一个我不知道如何解决的递归问题。能给个提示吗?
示例: 给定一个字符串和一个非空子字符串 sub,递归计算 sub 在字符串中出现的次数,且子字符串不重叠。
strCount("catcowcat", "cat") → 2
strCount("catcowcat", "cow") → 1
strCount("catcowcat", "dog") → 0
这是给定的方法
public int strCount(String str, String sub) {
//...
}
编辑(来自评论)我尝试过的内容:
public int strCount(String str, String sub) {
if(str == null || str.length() == 0 || str.indexOf(sub) == -1)
return 0;
if(str.indexOf(sub) != )
str = str.replace(sub,"");
return 1+strCount(str,sub);
}
【问题讨论】:
-
欢迎来到 Stack Overflow!请take the tour 了解该网站的运作方式以及此处的主题问题,并相应地编辑您的问题。另见:Why is "Can someone help me?" not an actual question?
-
对我来说这看起来像编码蝙蝠。请自己练习,然后带着真正的问题或问题回来。
-
您能展示一下您尝试了什么以及出了什么问题吗?根据此处提供的信息,很难确切地知道您需要什么样的帮助 - 如果我们可以看到您到目前为止所做的尝试,那么提供适当的指导会容易得多。另请参阅 minimal reproducible example 了解有关要包含哪些代码的信息。
-
离题..请先向我们展示您尝试执行的代码
-
这是我试过的,但没有奏效: public int strCount(String str, String sub) { if(str == null || str.length() == 0 || str. indexOf(sub) == -1) 返回 0; if(str.indexOf(sub) != ) str = str.replace(sub,"");返回 1+strCount(str,sub); }