Java Online Compiler
Example: PalindromeCheckRecursive in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// PalindromeCheckRecursive import java.util.Scanner; public class Main { // Helper method to preprocess the string private static String preprocessString(String s) { StringBuilder cleanedString = new StringBuilder(); for (char c : s.toCharArray()) { if (Character.isLetterOrDigit(c)) { cleanedString.append(Character.toLowerCase(c)); } } return cleanedString.toString(); } // Method to check for palindrome using recursion public static boolean isPalindromeRecursive(String s) { String cleaned = preprocessString(s); return checkRecursive(cleaned, 0, cleaned.length() - 1); } private static boolean checkRecursive(String s, int left, int right) { // Base Case 1: If left pointer crosses or meets right pointer, it's a palindrome if (left >= right) { return true; } // Base Case 2: If characters at current pointers don't match if (s.charAt(left) != s.charAt(right)) { return false; } // Recursive Step: Check the inner substring return checkRecursive(s, left + 1, right - 1); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Get input string from the user System.out.print("Enter a string to check for palindrome: "); String inputString = scanner.nextLine(); // Step 2: Check if it's a palindrome using the recursive method if (isPalindromeRecursive(inputString)) { System.out.println("'" + inputString + "' is a palindrome (Recursive Method)."); } else { System.out.println("'" + inputString + "' is NOT a palindrome (Recursive Method)."); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS