尝试递归地使用 StringBuilder,收到一个错误,表明它对 class 无效

Trying to use StringBuilder recursively, receiving an error indicating it is not valid for the class

编辑:我应该提到,这是一个专门要求递归解决方案的作业。

我正在尝试递归检查一个句子是否是 "Strict" 回文,这意味着它尊重空格 - "Able was I, ere I saw Elba!" - 或者它是否是 "ordinary" 回文,这意味着空格被忽略 - "A man, a plan, a canal, panama!".

如果我尝试 运行 这个程序只有字符串值,我会收到 Whosebug 错误。 StringBuilder 是可变的,所以我试图找到一种方法来代替它,但我找不到递归使用 StringBuilder 的任何示例(我假设是因为它没有意义,但我不知道为什么)

代码如下:

public static boolean isPalindrome(String userPal){


    if(userPal == null){
        return false;
    }
    else if( userPal.length() == 1 ){
        return true;
    }
    StringBuilder testAgainst = new StringBuilder();

    stringReversed(testAgainst);
    // String testAgainst = stringReversed(userPal);

    return userPal.equals( testAgainst );
}


public static StringBuilder stringReversed(StringBuilder toReverse){
    StringBuilder reversed = new StringBuilder(toReverse);

    if(toReverse == null){
        return null;
    }
    else if(toReverse.length() <= 1){
        return reversed;
    }

    System.out.println("This is the reverse string as it progresses: " + reversed);

    // return stringReversed( reversed.substring(1)+ reversed.charAt(0) );
    return stringReversed( reversed.substring(1, reversed.length() - 1 ) ); 

}

现在我在 "return StringReversed" 行收到一条错误消息:PalindromeCheck 类型中的方法 stringReversed(StringBuilder) 不适用于参数 (String)

PalindromeCheck 是 class 它所在的名称。

我一直在疯狂地搜索,但对于这样一个微妙的问题,这似乎是一个愚蠢的解决方案,我找不到答案。我不确定我哪里出错了,或者是什么导致了这些问题。

如果这里有人能帮助我理解,我将不胜感激。

谢谢,

克里斯

您需要初始化 StringBuilder 中的值,并且 StringBuilder 已经有一个 reverse 方法(但 return 是一个新的 StringBuilder 方法)。保存该调用的 return 值或内联使用它。喜欢,

public static boolean isPalindrome(String userPal) {
    if (userPal == null) {
        return false;
    } else if (userPal.length() < 2) {
        return true;
    }
    StringBuilder testAgainst = new StringBuilder(userPal);
    return userPal.equals(testAgainst.reverse().toString());
}

消除StringBuilder并迭代String的前半部分与后半部分比较字符。喜欢,

char[] arr = userPal.toCharArray();
for (int i = 0; i < arr.length / 2; i++) {
    if (arr[i] != arr[arr.length - 1 - i]) {
        return false;
    }
}
return true;

对于递归版本,

public static boolean isPalindrome(String userPal) {
    if (userPal == null) {
        return false;
    } else if (userPal.length() < 2) {
        return true;
    } else if (userPal.length() == 2) {
        return userPal.charAt(0) == userPal.charAt(1);
    }
    return userPal.charAt(0) == userPal.charAt(userPal.length() - 1)
            && isPalindrome(userPal.substring(1, userPal.length() - 1));
}