Quick actions

cmd+k|ctrl+k

Navigation

Languages

Check if string is Palindrome in C#

Snippet info

Language

Csharp

Visibility

public

Author

patrykstachowiak

Created

2025-03-10T19:08:27.628687Z

Updated

2025-03-10T19:15:17.330435Z

using System;
using System.Collections.Generic;
using System.Linq;

class MainClass {
    static void Main() {
        Console.WriteLine($"For sentence 'Kayak' is: {CheckIfSentenceIsPalindrome("Kayak")}");
        Console.WriteLine($"For sentence 'Kozak' is: {CheckIfSentenceIsPalindrome("Kozak")}");
        Console.WriteLine($"For sentence 'To jest juz za dlugie' is: {CheckIfSentenceIsPalindrome("To jest juz za dlugie")}");
        Console.WriteLine($"For sentence 'A man, a plan, a canal, Panama!' is: {CheckIfSentenceIsPalindrome("A man, a plan, a canal, Panama!")}");
        Console.WriteLine($"For sentence 'Was it a car or a cat I saw?' is: {CheckIfSentenceIsPalindrome("Was it a car or a cat I saw?")}");
    }
    
    // Time O(n) & Space O(1)
    private static bool CheckIfSentenceIsPalindrome(string word){
        if (word.Length < 1) return true;
        
        int leftSideIndex = 0;
        int rightSideIndex = word.Length-1;
        
        while (leftSideIndex < rightSideIndex)
        {
            while (leftSideIndex < rightSideIndex && !Char.IsLetterOrDigit(word[leftSideIndex])) {
                leftSideIndex++;
            }
            while (leftSideIndex < rightSideIndex && !Char.IsLetterOrDigit(word[rightSideIndex])) {
                rightSideIndex--;
            }

            if (Char.ToLower(word[leftSideIndex]) != Char.ToLower(word[rightSideIndex])) return false;
            
            leftSideIndex++;
            rightSideIndex--;
        }
        return true;
    }
}
INFO