我正在为 Java 进行编码 bat 练习,我遇到了一个问题:Eclipse 返回正确的值,而编码 bat 环境却没有。 我正在解决的问题是:
给定一个字符串和一个非空子字符串 sub,如果至少 n 个 sub 副本出现在字符串中的某处(可能有重叠),则递归计算。 N 将是非负数。
strCopies("catcowcat", "cat", 2) → true
strCopies("catcowcat", "cow", 2) → false
strCopies("catcowcat", "cow", 1) → true
对于 strCopies("iiijjj", "i", 3) 的情况,我的代码在编码 bat 中运行返回 false,而在 eclipse 中则返回 true。对于所有其他情况,我的代码在 eclipse 中返回的值与编码 bat 中的值相同。由于我已经在编码 bat 环境中遇到了无法解释的行为,这可能是一个错误吗?
我通过以下方式调用该方法:
System.out.println(p.strCopies("iiijjj", "i", 3));
我的代码是:
int count;
public boolean strCopies(String str, String sub, int n) {
if (str.indexOf(sub) != -1) {
count++;
strCopies(str.substring(str.indexOf(sub)+1), sub, n);
}
if (count == n) {
return true;
}
else {
count = 0;
return false;
}
}
最佳答案
这是一种可能的解决方案
public boolean strCopies(String str, String sub, int n) {
if(str.isEmpty() && n > 0 ) return false;
if(str.isEmpty() && n == 0 ) return true;
if( str.length() >= sub.length() &&
str.substring(0,sub.length()).equals(sub) ){
return strCopies( str.substring(1) , sub , n-1 );
}
return strCopies(str.substring(1) , sub , n);
}
关于java - 编码 bat 和 eclipse 的不同结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42330852/