Valid Palindrome - String - Easy - LeetCode
💻 coding

Valid Palindrome - String - Easy - LeetCode

1 min read 226 words
1 min read
ShareWhatsAppPost on X
  • 1A string is considered a palindrome if it reads the same forwards and backwards, ignoring non-alphanumeric characters and case.
  • 2The solution involves two pointers moving towards the center of the string, checking characters for equality after filtering.
  • 3The algorithm has a time complexity of O(n) and a space complexity of O(1), making it efficient for this problem.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A string is considered a palindrome if it reads the same forwards and backwards, ignoring non-alphanumeric characters and case."

Valid Palindrome - String - Easy - LeetCode

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);
 }
 }
}

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 4 June 2020 · 1 min read · 226 words

Part of AskGif Blog · coding

You might also like