首页 > 解决方案 > 递归和字符串相等函数的问题

问题描述

' 该代码假设在 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);
    }
}

标签: javarecursionequals

解决方案


你是对的,问题在第 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);
    }
}

推荐阅读