Palindromes
Compare a string from both ends
A palindrome reads the same from left to right and from right to left. There is no need to create a reversed copy of the string just to check it: we can compare symmetric characters with two pointers.
static boolean isPalindrome(String text) {
int left = 0;
int right = text.length() - 1;
while (left < right) {
if (text.charAt(left) != text.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
If even one pair differs, the answer is already known and the algorithm stops. In the worst case, roughly half of the character pairs are checked, so the time complexity is O(n) and the extra space is O(1).
Checking part of a string
Many problems require checking not the whole string but a range between two indexes. In that case, it is useful to pass the boundaries directly to the function instead of creating a separate substring.
static boolean isPalindrome(String text, int left, int right) {
while (left < right) {
if (text.charAt(left++) != text.charAt(right--)) {
return false;
}
}
return true;
}
This version is convenient to reuse inside larger algorithms:
the boundaries already identify the required fragment, and no extra String object is created.
Problem rules may change the comparison
Sometimes letter case must be ignored, while spaces and punctuation should be skipped. The two-pointers idea remains the same, but before comparison each pointer moves to the next meaningful character. It is important to follow the rules of the specific problem rather than automatically normalizing every string.
left < right finishes successfully immediately.