LeetCode 125 requires receiving a string and checking if it is a valid palindrome. I have done this and am confident with an int and a single word, but this question requires the use a of a sentence with non-alphanumeric characters. The function must ignore non-alphanumeric characters and whitespaces.
public bool isPalindrome(string s) {
s = System.Text.RegularExpressions.Regex.Replace(s, @"\W|_", "");
if (s == null || s == "" || s.Length == 1 || s == " ")
{
return true;
}
for (int i = 0, j = s.Length - 1; i <= s.Length / 2 && j >= s.Length /2;i--,j++)
{
if (Char.ToLower(s[i]) == Char.ToLower(s[j]))
{
continue;
}
return false;
}
return true;
}
It is my first time ever using Regex, maybe that gives my function a performance hit? Would it be better if I could implement this without Regex?
Example inputs are: "a man, a plan, a canal: Panama"
-- returns true
, "race a car"
-- returns false
, "a man, a plan, a canal -- Panama"
-- returns true
. The stats on this are: Runtime 136 ms, faster than 11.75% of c# submissions
.
i--,j++
. I'd start with.Replace(s, @"[\W_]+", "").ToLower();
but I've never written C# \$\endgroup\$