Java 递归回文法调试

Java 递归回文法调试,java,debugging,Java,Debugging,我正在尝试编写一个方法来测试字符串是否是回文。这就是我到目前为止所做的: public static boolean isPalindrome(String word) { boolean flag = false; if (word.length() < 2) { flag = true; } else if (word.charAt(0) == word.charAt(word.length() - 1)) { flag = i

我正在尝试编写一个方法来测试字符串是否是回文。这就是我到目前为止所做的:

public static boolean isPalindrome(String word) {
    boolean flag = false;

    if (word.length() < 2) {
        flag = true;
    } else if (word.charAt(0) == word.charAt(word.length() - 1)) {
        flag = isPalindrome(word.substring(1, word.length() - 2));
    }

    return flag;
}
public静态布尔值isAlindrome(字符串字){
布尔标志=假;
if(word.length()<2){
flag=true;
}else if(word.charAt(0)=word.charAt(word.length()-1)){
flag=isAlindrome(word.substring(1,word.length()-2));
}
返回标志;
}

我遇到的问题是,这个方法对于格式<代码>“AAABA”的字符串始终返回true,其中应该导致false通过堆栈传播的对在字符串的中间。我把头撞在墙上,想看看我的错误在哪里,但没有用。也许一双新的眼睛会看到我错过的东西

在递归调用中,应该从字符串长度中减去1,而不是2:

// start index inclusive, end index exclusive
flag = isPalindrome(word.substring(1, word.length() - 1));  

更改
子字符串(startIndex,endIndex)
方法中的
endIndex
。请注意,根据Java文档:

公共字符串子字符串(int-beginIndex,int-endIndex) 返回作为此字符串的子字符串的新字符串。子字符串从指定的beginIndex开始,并延伸到索引endIndex-1处的字符

将其更改为:

word.substring(1, word.length() - 1)
因此,假设
word=“aaba”
,此方法将返回
“ab”


此外,您还可以通过去掉
标志
并直接返回结果来简化代码:

public static boolean isPalindrome(String word)
{
    if (word.length() < 2) {
        return true;
    } else if (word.charAt(0) == word.charAt(word.length() - 1)) {
        return isPalindrome(word.substring(1, word.length() - 1));
    } else {
        return false;
    }
}
public静态布尔值isAlindrome(字符串字)
{
if(word.length()<2){
返回true;
}else if(word.charAt(0)=word.charAt(word.length()-1)){
返回isAlindrome(word.substring(1,word.length()-1));
}否则{
返回false;
}
}
试试这个

public static boolean isPalindrome(String word) {
 if(word.length() == 0 || word.length() == 1)
     return true; // If length is 0 or 1 then it is palindrome

 if(word.charAt(0) == word.charAt(word.length()-1))
     return isPalindrome(word.substring(1, word.length()-1));
     //Check the first and last char of the string if they are same
     //then continue the same for a substring by removing the first
     //and last character. And continue this until the string completes

 return false; //I fthe case doesn't match

}

尝试使用一些打印语句查看每次比较的字符。这将有助于缩小问题范围。所有这些都与返回word.equals(newstringbuilder(word.reverse().toString())相反?@JoshM这是一个有用的递归练习……公平地说,我没有意识到这些要求,只是建议有其他方法来实现它:PThanks这么多!我知道这是一件很简单的事情,我会因为看不见而自责。谢谢你的及时回复。是的,我应该注意到的。谢谢你指出!我使用的索引才是问题所在。非常感谢。