在核心 Java 中使用递归机制在另一个字符串中查找字符串 [英] Finding a String in another String Using Recursion Mechanism in Core Java
问题描述
我有以下问题陈述
PS:给定一个字符串str"和一个非空子字符串sub",如果sub"的至少N"个副本出现在字符串某处"中,则计算递归",可能带有重叠".N 将为非负.
示例如下
strCopies("catcowcat", "cat", 2) → true
strCopies("catcowcat", "cow", 2) → false
strCopies("catcowcat", "cow", 1) → true
strCopies("iiijjj", "ii", 2) → true
我已经编写了如下所示的代码(没有递归)并且对于少数测试用例运行良好,除了其他标记为 FAIL 的测试用例.
I have written the code as shown below(without recursion) and is working fine for few test cases,except for others which are marked as FAIL.
:::代码如下图:::
public boolean strCopies(String str, String sub, int n) {
int len = sub.length();
int result=0;
if(len>0){
int start = str.indexOf(sub);
while(start !=-1){
result++;
start = str.indexOf(sub,start+len);
}
}
if(result==n){
return true;
}else return false;
}
运行上述代码如下(粗体标记为失败的测试用例)
Runs for above code as shown below(Marked in BOLD are FAILED TEST CASES)
预期本次运行
strCopies("catcowcat", "cat", 2) → true true OK
strCopies("catcowcat", "cow", 2) → false false OK
strCopies("catcowcat", "cow", 1) → true true OK
strCopies("iiijjj", "ii", 2) → 真假失败
strCopies("iiiiij", "iii", 3) → 真假失败
strCopies("ijiiiiij", "iiii", 2) → 真假失败
你能检查一下并让我知道 FAIL TEST CASES 的代码有什么问题吗?我无法考虑重叠场景.
推荐答案
嗯,你的第一个问题是你的方法不是递归的.我怀疑您想使用 substring
以及 indexOf
...
Well, your first problem is that your method isn't recursive. I suspect you want to work with substring
as well as indexOf
...
至于为什么您当前的方法不起作用,我怀疑是因为您使用 start + len
而不是 start + 1
来查找下一个起始位置.因此,当试图在iii"中找到ii"时,您应该首先查看位置 0,然后查看位置 1——目前您正在查看位置 2,这意味着它不会找到从 1 开始的第二个ii".
As for why your current method isn't working, I suspect it's because you're using start + len
instead of start + 1
to find the next starting position. So when trying to find "ii" in "iii", you should first look at position 0, then position 1 - currently you're looking at position 2, which would mean it wouldn't find the second "ii" starting at 1.
这篇关于在核心 Java 中使用递归机制在另一个字符串中查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!