有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java试图递归使用StringBuilder,但收到一个错误,指示它对类无效

编辑:我应该提到,这是针对一个特别需要递归解决方案的赋值

我试图递归地检查一个句子是否是“严格”回文,这意味着它尊重空格——“在我看到厄尔巴之前,我是能干的!”或者,如果它是一个“普通”回文,意味着空间被忽略——“一个人,一个计划,一条运河,巴拿马!”

如果我尝试仅使用字符串值运行此程序,则会出现StackOverflow错误。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”行上收到一个错误,该行表示:类型回文检查中的StringReversed(StringBuilder)方法不适用于参数(String)

PalindromeCheck是它所在的类的名称

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

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

谢谢,

克里斯


共 (1) 个答案

  1. # 1 楼答案

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

    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));
    }