Reverse a String and Check a Palindrome
csharpC# and .NETbeginnerinterview-prep
Two classic warm-up problems: reverse a string in place without Array.Reverse, and test a palindrome while ignoring case and punctuation.
Console.WriteLine(Reverse("interview")); // weivretni
Console.WriteLine(IsPalindrome("A man, a plan, a canal: Panama")); // True
Console.WriteLine(IsPalindrome("Hello")); // False
// Swaps characters from both ends of a char array. O(n) time, no Array.Reverse or LINQ.
static string Reverse(string text)
{
char[] chars = text.ToCharArray();
for (int left = 0, right = chars.Length - 1; left < right; left++, right--)
(chars[left], chars[right]) = (chars[right], chars[left]);
return new string(chars);
}
// Two pointers from both ends, skipping punctuation and ignoring case. O(n) time, O(1) extra space.
static bool IsPalindrome(string text)
{
int left = 0, right = text.Length - 1;
while (left < right)
{
if (!char.IsLetterOrDigit(text[left])) { left++; continue; }
if (!char.IsLetterOrDigit(text[right])) { right--; continue; }
if (char.ToLowerInvariant(text[left]) != char.ToLowerInvariant(text[right])) return false;
left++;
right--;
}
return true;
}