Palindrome Check (Recursive)
Problem
Read one word. Print true if it reads the same from left to right and from right to left. Use recursion: compare the outer two letters, then check the inside.
Constraints
- 1 <= length <= 5000
Examples
Input
racecar
Output
true
Solutions
Passing two indexes instead of a new substring avoids copying the string on every call. Each call makes the problem two letters smaller.
/*
* Problem : Palindrome check.
* Input : One word.
* Output : true or false.
* Approach: Recursion on indexes.
* Time : O(n)
* Space : O(n) call stack
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: Check the part of the word from index left to index right.
static boolean check(String s, int left, int right) {
// Step 2: Base case. One letter or no letter is always a palindrome.
if (left >= right) {
return true;
}
// Step 3: If the outer letters differ, stop. Otherwise check the inside.
if (s.charAt(left) != s.charAt(right)) {
return false;
}
return check(s, left + 1, right - 1);
}
// This method solves the task. It receives the input and returns the answer.
static boolean solve(String s) {
return check(s, 0, s.length() - 1);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.hasNextLine() ? scanner.nextLine() : "";
System.out.println(solve(s));
}
}
Hints (1)
- What is the base case?