java中的递归方法检测回文

时间:2015-09-09 02:05:24

标签: java recursion palindrome

我试图跟踪检测单词是否是回文的递归方法:

public static boolean isPalindrome(String word) {
    if (word.length() == 0 || word.length() == 1) {
        return true; 
    } else if (word.charAt(0) == word.charAt(word.length() - 1)) {
        return isPalindrome(word.substring(1, word.length() - 1)); 
    } else {
        return false;
    } 
}

我用过的词是:“abba”。该方法的第一个实例采用else方式,因为对第一个if条件的求值,所以它在if else语句中求条件得到一个true作为结果,然后该方法返回带有单词“bb”的方法的运行。递归再次运行该方法:“bb”的长度不是0或1,然后采用else方式,并评估第一个'b'是否等于第二个'b',为真,所以返回运行同样的方法再次,但现在有一个子字符串,从位置1(beginIndex)'b'中的字符开始,并以位置0(endIndex)中的字符结束,但beginIndex大于endIndex,这应该抛出IndexOutOfBoundsException。 ..但是方法有效。有人可以向我解释一下吗?谢谢

2 个答案:

答案 0 :(得分:0)

在第二次迭代中,单词为bb。这意味着长度为2

您的子字符串是word.substring(1, 1)。因此它不会(并且正确地)抛出异常,而是返回一个空字符串。

答案 1 :(得分:0)

添加一些println可以帮助您进行调试,请检查here

public static boolean isPalindrome(String word){
    System.out.println("Checking "+word+" length: "+word.length());
    if(word.length()==0 || word.length()==1){
        System.out.println("Base Case");
        return true; 
    } else if(word.charAt(0)==word.charAt(word.length()-1)){
        System.out.println("Resursive case substring(1,"+(word.length()-1)+")");
        return isPalindrome(word.substring(1, word.length()-1)); 
    }else {
        return false;
    } 
}

Checking abba length: 4
Resursive case substring(1,3)
Checking bb length: 2
Resursive case substring(1,1)
Checking  length: 0
Base Case

正如您在第二次递归调用中看到的那样,您有"bb"并且您要检查substring(1,1),文档说明:

  

IndexOutOfBoundsException - 如果beginIndex为负数,或者endIndex大于此String对象的长度,或者beginIndex大于endIndex。

beginIndex不是>比endIndex所以没有抛出异常。您可以说子字符串在索引1处的字符之后开始,并在索引0处的字符之后通过解释

结束
  

返回一个新字符串,该字符串是此字符串的子字符串。子字符串从指定的beginIndex开始,并扩展到索引endIndex - 1处的字符。因此子字符串的长度为endIndex-beginIndex。

|      b       |       b      |
                ^
                beginIndex (starts at 1)
              ^
              endIndex - 1 (ends past 0)