Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.String
{
public class IsPalindromeSoln
{
public bool IsPalindrome(string s)
{
int i = 0;
int j = s.Length - 1;
while (i < j)
{
if (!IsAlphaNumeric(s[i]))
{
i++;
continue;
}
if (!IsAlphaNumeric(s[j]))
{
j--;
continue;
}
if(char.ToLower(s[i]) != char.ToLower(s[j]))
{
return false;
}
i++;
j--;
}
return true;
}
private bool IsAlphaNumeric(char v)
{
if( ( v>= 48 && v <= 57 ) || (v >= 65 && v <= 90) || (v >= 97 && v <= 122))
{
return true;
}
return false;
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Unit Tests:
using LeetCode.AskGif.Easy.String;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.String
{
[TestClass]
public class IsPalindromeSolnTests
{
[TestMethod]
public void IsPalindromeSoln_First()
{
var s = "A man, a plan, a canal: Panama";
var output = true;
var res = new IsPalindromeSoln().IsPalindrome(s);
Assert.AreEqual(res, output);
}
[TestMethod]
public void IsPalindromeSoln_Second()
{
var s = "race a car";
var output = false;
var res = new IsPalindromeSoln().IsPalindrome(s);
Assert.AreEqual(res, output);
}
}
}



