How to check if a string is a palindrome ignoring case and non-alphanumeric characters in Go

2 Answers

0 votes
package main

import (
    "fmt"
    "unicode"
)

func isPalindrome(s string) bool {
    var normalized []rune

    // Remove non-alphanumeric characters and convert to lowercase
    for _, ch := range s {
        if unicode.IsLetter(ch) || unicode.IsDigit(ch) {
            normalized = append(normalized, unicode.ToLower(ch))
        }
    }

    fmt.Println(string(normalized))

    // Check if the string is equal to its reverse
    n := len(normalized)
    for i := 0; i < n/2; i++ {
        if normalized[i] != normalized[n-1-i] {
            return false
        }
    }

    return true
}

func main() {
    s := "+^-Ab#c!D 50...#  05*()dcB[]A##@!$"
    
    fmt.Println(isPalindrome(s))
}



/*
run:

abcd5005dcba
true

*/

 



answered Aug 10, 2025 by avibootz
0 votes
package main

import (
    "fmt"
    "regexp"
    "strings"
)

func isPalindrome(s string) bool {
    // Compile regex to match non-alphanumeric characters
    re := regexp.MustCompile(`[^a-zA-Z0-9]+`)
    // Replace them with empty string and convert to lowercase
    normalized := strings.ToLower(re.ReplaceAllString(s, ""))

    fmt.Println(normalized)

    // Check if the string is equal to its reverse
    n := len(normalized)
    for i := 0; i < n/2; i++ {
        if normalized[i] != normalized[n-1-i] {
            return false
        }
    }

    return true
}

func main() {
    s := "+^-Ab#c!D 50...#  05*()dcB[]A##@!$"
    
    fmt.Println(isPalindrome(s))
}




/*
run:

abcd5005dcba
true

*/

 



answered Aug 10, 2025 by avibootz
...