Sponsored
Sponsored
This approach employs two pointers: one starting at the beginning of the string and the other at the end. The algorithm checks if the characters at these pointers are the same, ignoring case and non-alphanumeric characters. If they match, both pointers move inward. If they don't or if any pointer surpasses the other, the string is not a palindrome.
Time Complexity: O(n), where n is the length of the string, because we go through the string at most once.
Space Complexity: O(1), as we use a constant amount of space.
1using System;
2
3public class Solution {
4 public bool IsPalindrome(string s) {
5 int left = 0, right = s.Length - 1;
6 while (left < right) {
7 while (left < right && !Char.IsLetterOrDigit(s[left])) left++;
8 while (left < right && !Char.IsLetterOrDigit(s[right])) right--;
9 if (Char.ToLower(s[left]) != Char.ToLower(s[right])) return false;
10 left++;
11 right--;
12 }
13 return true;
14 }
15
16 public static void Main() {
17 Solution solution = new Solution();
18 string s = "A man, a plan, a canal: Panama";
19 Console.WriteLine(solution.IsPalindrome(s));
20 }
21}This C# method verifies if a string is a palindrome, maneuvering two pointers and comparing respective characters while disregarding their cases and skipping non-alphanumeric characters.
This approach first cleans the input string by removing non-alphanumeric characters and converting all letters to lowercase. It then compares the normalized string to its reverse to determine if it is a palindrome.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(n), because the cleaned string and its reverse require extra space proportional to n.
1const isPalindrome = function(s)
In JavaScript, this solution uses regular expressions to filter and clean the input and then leverage string manipulation techniques to check if cleaned string equals its reverse.