Skip to content

Commit d056191

Browse files
committed
Add TwoPointerPalindrome.java with test cases and comments
1 parent a21abe6 commit d056191

File tree

4 files changed

+67
-79
lines changed

4 files changed

+67
-79
lines changed

src/main/java/com/thealgorithms/strings/Palindrome.java

Lines changed: 0 additions & 58 deletions
This file was deleted.
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Check if a given string is a palindrome using the two-pointer technique.
3+
* A palindrome is a string that reads the same forward and backward.
4+
*
5+
* Example: "level", "madam", "12321" are palindromes.
6+
*
7+
* Author: Sushma
8+
*/
9+
10+
package com.thealgorithms.strings;
11+
12+
public class TwoPointerPalindrome {
13+
14+
/**
15+
* This method checks if the given string is a palindrome using two pointers.
16+
*
17+
* @param s The input string to check
18+
* @return true if the string is a palindrome, false otherwise
19+
*/
20+
public static boolean isPalindrome(String s) {
21+
22+
// If the string is null or has only 1 or 0 characters, it's a palindrome
23+
if (s == null || s.length() <= 1) {
24+
return true;
25+
}
26+
27+
// Initialize two pointers: left starting from the beginning,
28+
// right starting from the end of the string
29+
int left = 0;
30+
int right = s.length() - 1;
31+
32+
// Loop until the two pointers meet in the middle
33+
while (left < right) {
34+
35+
// If characters at left and right don't match, it's not a palindrome
36+
if (s.charAt(left) != s.charAt(right)) {
37+
return false;
38+
}
39+
40+
// Move the left pointer to the right
41+
left++;
42+
43+
// Move the right pointer to the left
44+
right--;
45+
}
46+
47+
// If all characters matched, then it's a palindrome
48+
return true;
49+
}
50+
}

src/test/java/com/thealgorithms/strings/PalindromeTest.java

Lines changed: 0 additions & 21 deletions
This file was deleted.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package com.thealgorithms.strings;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
import org.junit.jupiter.api.Test;
5+
6+
public class TwoPointerPalindromeTest {
7+
8+
@Test
9+
void testPalindrome() {
10+
assertTrue(TwoPointerPalindrome.isPalindrome("madam"));
11+
assertTrue(TwoPointerPalindrome.isPalindrome("racecar"));
12+
assertTrue(TwoPointerPalindrome.isPalindrome("a"));
13+
14+
assertFalse(TwoPointerPalindrome.isPalindrome("hello"));
15+
assertFalse(TwoPointerPalindrome.isPalindrome("world"));
16+
}
17+
}

0 commit comments

Comments
 (0)