【问题标题】:problem with recursion and string equal function递归和字符串相等函数的问题
【发布时间】:2020-07-30 14:46:56
【问题描述】:

' 该代码假设在 str 的子字符串中查找目标。它将 str 的子字符串与目标进行比较。它从第一个子字符串开始比较(由从 0 索引到 str 的 target.length-1 索引的字符组成)。如果 substring 不等于 target 它从 str 中删除第一个字符并再次将其返回给函数。如果 str 长度小于目标长度,则返回 false。 '

'例如,如果 str = "superman" & target = "man"。与目标“man”相比,第一个子字符串是“sup”。这是错误的,因此“s”被删除。与“man”相比,下一个子字符串是“upe”,再次为假,因此“u”被删除。下一个带有“man”和“p”的“per”被删除。'

'直到子字符串是“man”与目标“man”比较。在这里,它应该返回 true,但它没有,而是继续删除“m”并继续'

'很可能问题出在第 7 行'

public static boolean contains(String str, String target) {
    if(str == null || target == null) {   //null check
        return false;
    }
    if(str.length() < target.length()) {  // when string has less size than target, naturally its false
        return false;
    } else if(target.equals(str.substring(0,target.length()-1))) {  //this is where the problem is
                                                                    //more specifically, it isn't comparing the strings. 
                                                                    //Here if str and target are equal they should return true, but when the target is equal to str, it doesnt return true, instead treats it is if target is not equal to str.
        return true;
    } else {
        return contains(str.substring(1),target);
    }
}

【问题讨论】:

  • 你为什么不简单地使用str.contains(target)?这已经在标准 java 库中可用
  • target.length()-1 是错误的。再次阅读String.substring 的文档。或者打印出str.substring(...)的结果
  • 每个优秀的程序员都知道如何调试他的代码。假设您还没有阅读它,也许这会有所帮助:How to debug small programs
  • @davidgiga1993 重点是制作我自己的函数(类项目)。
  • @JohannesKuhn 是的,当我删除 -1 时它起作用了,谢谢。没怎么用过字符串函数。

标签: java recursion equals


【解决方案1】:

你是对的,问题出在第 7 行,目标不用减 1。

方法:

public static boolean mycontains(String str, String target) {
    if(str == null || target == null) {   
        return false;
    }
    if(str.length() < target.length()) {  
        return false;
    } else if(target.equals(str.substring(0,target.length()))) {  
        return true;
    } else {
        return mycontains(str.substring(1),target);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2015-05-12
    相关资源
    最近更新 更多