当前位置: 代码迷 >> java >> 简单的递归代码错误返回
  详细解决方案

简单的递归代码错误返回

热度:74   发布时间:2023-07-17 20:16:24.0

为什么我的代码应返回true,返回false?

如果str2包含零个或多个字符,则strstring应该返回true,然后是str1的所有字符,然后是零个或多个字符。 如果a没有出现在b中的任何位置,则该方法应返回false。

我不是在寻找另一种方法来返回正确的输出,但是想找出我的代码错误的原因。

public class stringRecursionPractice{
    public static void main(String[] args){
        String str1 = "abc"; 
        String str2 = "abc";
        System.out.println(isSubstring(str1, str2));
    }

    /*
     * Returns the string containing only the first character of the
     * specified string.
     */
    public static String head(String s) {
        return s.substring(0, 1);
    }

    /*
     * Returns the string containing the all the characters but the first
     * character in the specified string.
     */
    public static String tail(String s) {
        return s.substring(1);
    }

    public static boolean isSubstring(String str1, String str2){
    if(str1.length() == 1 && str1.charAt(0) == str2.charAt(0)){
        return true; 
    }

    if(head(str1).equals(head(str2))){
        isSubstring(tail(str1), tail(str2)); 
    }

    return false; 
    }
}

您的递归调用应返回结果:

if(head(str1).equals(head(str2))){
    return isSubstring(tail(str1), tail(str2)); 
}
  相关解决方案