简体   繁体   中英

To check if string is palindrome using recursion?

There is something wrong with my code as one the testcase in my assignment is coming out wrong, giving me runtime error when I submit the code online. That testcase could be any String. I believe that everything is fine with the code as I have checked it manually for many testcases.

HERE IS THE CODE

public static boolean isStringPalindrome(String input) {
    if(input.length()==0 || input.length()==1)
        return true;

    int first = 0;
    int last = input.length()-1;

    if(input.charAt(first) != input.charAt(last))
        return false;

    String str="";
    for(int i=first+1;i<last;i++){
        str = str+input.charAt(i); 
    }
    boolean sa = isStringPalindrome(str);
    return sa; 
}

Sample Input

racecar

Output

true   

Sample Input

pablo

Output

false   

Your code appears to be overly complicated for recursively testing if the String is a palindrome. Something like,

public static boolean isStringPalindrome(String input) {
    if (input == null) {
        return false;
    } else if (input.isEmpty() || input.length() == 1) {
        return true;
    }
    int len = input.length() - 1;
    return input.charAt(0) == input.charAt(len) //
            && isStringPalindrome(input.substring(1, len));
}

Is recursive without embedding a for loop. Because if you can do that, you should do something like

public static boolean isStringPalindrome(String input) {
    if (input == null) {
        return false;
    } else if (input.isEmpty() || input.length() == 1) {
        return true;
    }
    int len = input.length();
    for (int i = 0; i <= len / 2; i++) {
        if (input.charAt(i) != input.charAt(len - 1 - i)) {
            return false;
        }
    }
    return true;
}

A simpler way to check for palindrome can be:

public static boolean isPalindrome(String s)
{   if (input == null)
        return false;
    else if(s.length() == 0 || s.length() == 1)
        return true;

    /* check for first and last char of String:
     * if they are same then do the same thing for a substring
     * with first and last char removed. and carry on this
     * until you string completes or condition fails.
     */
    if(s.charAt(0) == s.charAt(s.length()-1))
        return isPalindrome(s.substring(1, s.length()-1));

    return false;
}

Update

You are getting runtime error(NZEC) which means non-zero exit code . It means your program is ending unexpectedly. I don't see any reason except that your program doesn't have a null check. Otherwise, I have gone through your code carefully, you are doing the same thing which I have suggested.

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