Skip to content

Add TwoPointerPalindrome.java with tAdd TwoPointerPalindrome.java using two-pointer techniqueest cases and comments #6294

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 0 additions & 58 deletions src/main/java/com/thealgorithms/strings/Palindrome.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/**
* Check if a given string is a palindrome using the two-pointer technique.
* A palindrome is a string that reads the same forward and backward.
*
* Example: "level", "madam", "12321" are palindromes.
*
* Author: Sushma
*/

package com.thealgorithms.strings;

public class TwoPointerPalindrome {

/**
* This method checks if the given string is a palindrome using two pointers.
*
* @param s The input string to check
* @return true if the string is a palindrome, false otherwise
*/
public static boolean isPalindrome(String s) {

// If the string is null or has only 1 or 0 characters, it's a palindrome
if (s == null || s.length() <= 1) {
return true;
}

// Initialize two pointers: left starting from the beginning,
// right starting from the end of the string
int left = 0;
int right = s.length() - 1;

// Loop until the two pointers meet in the middle
while (left < right) {

// If characters at left and right don't match, it's not a palindrome
if (s.charAt(left) != s.charAt(right)) {
return false;
}

// Move the left pointer to the right
left++;

// Move the right pointer to the left
right--;
}

// If all characters matched, then it's a palindrome
return true;
}
}
21 changes: 0 additions & 21 deletions src/test/java/com/thealgorithms/strings/PalindromeTest.java

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.thealgorithms.strings;

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

public class TwoPointerPalindromeTest {

@Test
void testPalindrome() {
assertTrue(TwoPointerPalindrome.isPalindrome("madam"));
assertTrue(TwoPointerPalindrome.isPalindrome("racecar"));
assertTrue(TwoPointerPalindrome.isPalindrome("a"));

assertTrue(TwoPointerPalindrome.isPalindrome(null));
assertTrue(TwoPointerPalindrome.isPalindrome(""));

assertFalse(TwoPointerPalindrome.isPalindrome("hello"));
assertFalse(TwoPointerPalindrome.isPalindrome("world"));
}
}
Loading