简体   繁体   中英

Java - Using Recursion to Find Palindrome

I am designing a util class that takes a string as a parameter and returns true if it is a palindrome(ex: input: radar ---> output: true) and returns false if it is not. For this class, I am using a linkedlist, however I don't know why there seems to be an error. Here is the stack trace:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
    at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
    at java.util.LinkedList.remove(LinkedList.java:525)
    at com.run.FindPalindromes.FindMain(FindPalindromes.java:20)
    at com.run.FindPalindromes.FindMain(FindPalindromes.java:16)
    at com.run.Test.main(Test.java:7)

And Here is the source code:

public boolean FindMain(String in){
    if(times == 0){
    search = new LinkedList(cc.convertStringToArraylist(in)); 
    times ++;
    FindMain(null);
    } else {
        if(search.get(search.size()-1).equals(search.get(0))){
            search.remove(0);
            search.remove(search.size());
            FindMain(null);
        } else {
            System.out.println("Not Palindrome");
            return false;
        }
    }

    return true;

}

search.remove(search.size()) should be search.remove(search.size() - 1) since lists are zero-based. If you have four elements your list indices run from 0 to 3, and so there is nothing at location 4.

Also your code as it stands won't handle empty lists very well, so that's something you need to check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM