1

I am having trouble rewriting the following code as a recursive method rather than using the for loop. The for loop tests to see if the String 'noSpaces' is a palindrome (the same forwards as it is backwards). The noSpaces String has no punctuation, spaces, or differences in capitalization.

Thanks for the help

    public boolean isRegularPalindrome(String noSpaces) {
    noSpaces = noSpaces.toUpperCase();
    String[] letters = new String[noSpaces.length()];
    for (int i = 0; i < letters.length; i++) {
        letters[i] = Character.toString(noSpaces.charAt(i));
    }

    for (int i = 0; i < letters.length / 2; i++) {
        if (!letters[i].equals(letters[letters.length - i - 1])) {
            return false;
        }
    }
    return true;
}
3
  • You've over-complicated your solution. There's no need to turn a string into an array of one-character strings. Just do if (noSpaces.charAt(i) != noSpaces.charAt(noSpaces.length() - 1 - i)) return false;. And then with this simple method, you might find it easier to turn it into a recursive one. Commented Mar 10, 2016 at 0:50
  • Is this a homework question? Commented Mar 10, 2016 at 0:51
  • stackoverflow.com/questions/4367260/… Commented Mar 10, 2016 at 0:55

2 Answers 2

2

There you go:

public static boolean isPalindrome(String input) {
    if (input.charAt(0) != input.charAt(input.length() - 1)) {
        // Missmatch. Not a palindrome!
        return false;
    } else if (input.length() > 1){
        // If there is more to test, continue.
        return isPalindrome(input.substring(1, input.length() - 1));
    } else {
        // All chars were tested, or 1 char input. Palindrome!
        return true;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It would be nice of you if you would accept one of the answers that you like ;)
2

Writing a recursive algorithm for anything requires base cases. For a palindrome, this would be a string of length 0 or length 1 -- if the string is length 0 or 1, it is a palindrome.
If the base cases aren't met, you check the first character against the last character.
If the characters aren't the same, return false.
If the characters are the same, return the recursive call to the string except for the first and last characters.
The code should look something like this.

public boolean isPalindrome(string str){
if (str.length == 0)
    return true;
else if (str.length == 1)
    return true;
else if(str.charAt(0) != str.charAt(str.length - 1)
    return false;
else
    return isPalindrome(str.substring(1, length - 1));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.