Palindrome check
A string is a palindrome if it reads the same in both directions. Compare from the outside in.
Watch it animatedStep through it, with the running line highlighted. Free with an account.The idea
Put one pointer at each end and walk them towards each other. The first mismatch proves it is not a palindrome. If they meet, it is.
Code
bool isPalindrome(const string& s) {
int l = 0, r = (int)s.size() - 1;
while (l < r) {
if (s[l] != s[r]) return false;
l++; r--;
}
return true;
}def is_palindrome(s: str) -> bool:
l, r = 0, len(s) - 1
while l < r:
if s[l] != s[r]: return False
l += 1; r -= 1
return Truepublic static bool IsPalindrome(string s) {
int l = 0, r = s.Length - 1;
while (l < r) {
if (s[l] != s[r]) return false;
l++; r--;
}
return true;
}Tips
- For "ignore case and punctuation" versions, skip characters where char.IsLetterOrDigit is false and compare with char.ToLowerInvariant.
In the .NET library
s.SequenceEqual(s.Reverse()) is the one-liner. It allocates and compares the full length, where two pointers stop at the first mismatch.