【发布时间】:2011-05-30 15:34:58
【问题描述】:
我有以下问题陈述
PS:给定一个字符串“str”和一个非空子字符串“sub”,如果“sub”的至少“N”个副本出现在“某处”中,则计算“递归”,可能带有“重叠”。 N 将是非负数。
Example are as shown belowstrCopies("catcowcat", "cat", 2) → truestrCopies("catcowcat", "cow", 2) → falsestrCopies("catcowcat", "cow", 1) → truestrCopies("iiijjj", "ii", 2) → true
我已经编写了如下所示的代码(没有递归),并且在少数测试用例中运行良好,除了标记为 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;
}
运行上述代码如下所示(用粗体标记为失败的测试用例)
Expected This RunstrCopies("catcowcat", "cat", 2) → true true OKstrCopies("catcowcat", "cow", 2) → false false OKstrCopies("catcowcat", "cow", 1) → true true OKstrCopies("iiijjj", "ii", 2) → true false FAILstrCopies("iiiiij", "iii", 3) → true false FAILstrCopies("ijiiiiij", "iiii", 2) → true false FAIL
您能否检查并告诉我 FAIL TEST CASES 的代码有什么问题?我无法考虑重叠场景。
【问题讨论】: