java - 编码 bat 和 eclipse 的不同结果

标签 java eclipse

我正在为 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/

相关文章:

java - 如何在 Java 调试详细信息格式化程序中将字节数组显示为字符串?

java - Fasterxml objectmapper 错误地将 java 对象转换为 json?

java - 使用两个类文件的用户定义的 Java 乘法表

java - 安卓 - "The method add(int, Fragment)..."

java - 如何做RandomBug代码

Android AOSP项目导入eclipse

java - 使用 Openweather API 获取特定日期的天气 - 解析 JSON 响应

java - 超链接下拉列表

java - 将 Activity 堆栈清除到顶部

android - 如何在 Eclipse 中安装较旧的 Android SDK 平台工具 23.0.1?