Friday, June 5, 2009

Solving Palindrome Using Recursion

This is a follow-up article about solving palindrome using recursion. While we solved this problem previously using iteration (link to previous article), I am demonstrating the way of solving it in a recursive manner.

public static void isPalindromeRecursive(String text){
text = text.toLowerCase().replaceAll("[\\W\\_*]", "");
if (helperFunction(text, 0, text.length()-1)) {
System.out.println("Is a Palindrome");
} else {
System.out.println("Is not a Palindrome");
}
}

private static boolean helperFunction(String input, int leftIndex, int rightIndex){
if (leftIndex < rightIndex) {
if (!(input.charAt(leftIndex) == input.charAt(rightIndex))) {
return false;
}
leftIndex++;
rightIndex--;
helperFunction(input, leftIndex, rightIndex);
}
return true;
}

0 comments:

Post a Comment