Video in progress
How do you check whether a string is a palindrome, ignoring spaces and letter case?
With two pointers: from the left and right I skip characters that aren't letters or digits, lowercase the rest and compare. No new string is built, time is O(n), memory is O(1).
📖 Answer
The easiest way is to clean the string, reverse it and compare:
String clean = s.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
return new StringBuilder(clean).reverse().toString().equals(clean);
It works, but it creates two extra strings. In an interview the next question is usually "can you do it without extra memory?":
static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
char a = s.charAt(i), b = s.charAt(j);
if (!Character.isLetterOrDigit(a)) { i++; continue; }
if (!Character.isLetterOrDigit(b)) { j--; continue; }
if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false;
i++; j--;
}
return true;
}
"A man, a plan, a canal: Panama" gives true. An empty string counts as a palindrome too. It's a plus if you mention that charAt doesn't work correctly with complex Unicode characters (emoji, surrogate pairs).
Sign up to mark studied questions and save your progress.