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;
}
Isaac
  • 11
  • 1
  • 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. – Klitos Kyriacou Mar 10 '16 at 00:50
  • Is this a homework question? – Sky Kelsey Mar 10 '16 at 00:51
  • http://stackoverflow.com/questions/4367260/creating-a-recursive-method-for-palindrome – Zoltán Mar 10 '16 at 00:55

2 Answers2

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));
}
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;
    }
}
Eduard Moraru
  • 770
  • 4
  • 9