递归Palindrome方法调试

时间:2014-01-26 04:50:30

标签: 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 = isPalindrome(word.substring(1, word.length() - 2));
    }

    return flag;
}

我遇到的问题是,对于"aaaba"形式的字符串,此方法始终返回true,其中应该导致false通过堆栈传播回来的对位于字符串的中间。我正在撞墙,试图看看我的错误在哪里,但无济于事。也许一双新鲜的眼睛会看到我失踪的东西?

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

更改endIndex方法中的substring(startIndex, endIndex)。请注意,根据Java Docs:

  

public String substring(int beginIndex,int endIndex)   返回一个新字符串,该字符串是此字符串的子字符串。子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1的字符。

将其更改为:

word.substring(1, word.length() - 1)

所以,假设word = "aaba",此方法将返回"ab"


此外,您可以通过删除flag并直接返回结果来简化代码:

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

答案 2 :(得分:1)

试试这个......

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

}