Palindrome计划出错

时间:2014-09-01 18:28:12

标签: java string recursion boolean palindrome

亲爱的Stack Overflow用户,

我的回文计划一直出错。代码如下:

public static boolean isPalindrome_r(String word){
    int beginning = 0;
    int end = word.length() - 1;

    if(word.charAt(beginning) == word.charAt(end)){
        return (isPalindrome_r(word.substring(1, word.length() - 1)));
    }
    else if (word.charAt(beginning) != word.charAt(end)){
        return false;
    }

    return false;
}

public static boolean isPalindrome_nr(String word){
    int beginning = 0;
    int end = word.length() - 1;

    boolean pd = true;

    for (int i = end; i>=0; i--){
        if(word.charAt(i) != word.charAt(end-i)){
            pd = false;
        }
    }

    return pd;
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Is the string a palindrome or not? ");
    String test = "test";
    String test_2 = "level";
    String test_3 = "application";
    System.out.println("Answer: " + isPalindrome_r(test));
    System.out.println("Answer: " + isPalindrome_r(test_2));
    System.out.println("Answer: " + isPalindrome_r(test_3));
    System.out.println("Answer: " + isPalindrome_nr(test));
    System.out.println("Answer: " + isPalindrome_nr(test_2));
    System.out.println("Answer: " + isPalindrome_nr(test_3));

}

关于递归版本的test_2的错误输出如下:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at assignment1cs.recursion.isPalindrome_r(recursion.java:12)
at assignment1cs.recursion.isPalindrome_r(recursion.java:12)
at assignment1cs.recursion.isPalindrome_r(recursion.java:12)
at assignment1cs.recursion.main(recursion.java:80)

请你帮我解决这个问题?

3 个答案:

答案 0 :(得分:2)

你没有停止条件。如果剩余的字符串长度<1,则应该终止递归。 4;

如果长度为1,则返回true 如果长度为2或3,则如果first = last,则返回true。

答案 1 :(得分:1)

试试这个(重要的是不要忘记s.length()&lt; 2)时的情况:

public static boolean isPalindrome(String s) {
        int length = s.length();
        if (s.isEmpty() || length == 1) 
            return true;
        return s.charAt(0) != s.charAt(length - 1) ? false : isPalindroma(s.substring(1,length - 1));
    }

答案 2 :(得分:0)

经过几轮执行后,word.substring(1, word.length() - 1)生成的子字符串长度可能为0。

因此,在递归的下一次迭代中: int end = word.length() - 1;将为-1 并且word.charAt(beginning) == word.charAt(end)将为word.charAt(0) == word.charAt(-1),从而导致您看到的运行时错误。