Skip to content

Commit 817cc9f

Browse files
authored
Create Palindrome.java
1 parent f9a9ccb commit 817cc9f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.recursion;
2+
3+
/*
4+
Check if a string is a palindrome using recursion.
5+
Example: "madam" → true, "hello" → false
6+
*/
7+
public final class Palindrome {
8+
private Palindrome() {
9+
throw new UnsupportedOperationException("Utility class");
10+
}
11+
12+
public static boolean isPalindrome(String str) {
13+
if (str == null) {
14+
throw new IllegalArgumentException("Null string not allowed");
15+
}
16+
return isPalindromeHelper(str, 0, str.length() - 1);
17+
}
18+
19+
private static boolean isPalindromeHelper(String str, int left, int right) {
20+
if (left >= right) {
21+
return true;
22+
}
23+
if (str.charAt(left) != str.charAt(right)) {
24+
return false;
25+
}
26+
return isPalindromeHelper(str, left + 1, right - 1);
27+
}
28+
}

0 commit comments

Comments
 (0)