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, no sign-in needed to watch.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
public 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;
}static boolean isPalindrome(String value) {
int left = 0, right = value.length() - 1;
while (left < right) {
if (value.charAt(left) != value.charAt(right)) return false;
left++; right--;
}
return true;
}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 TrueTips
- 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.