How to check whether a string is a palindrome, ignoring spaces and case in Go

1 Answer

0 votes
package main

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

func isPalindrome(s string) bool {
    // Normalize the string: remove spaces and convert to lowercase
    re := regexp.MustCompile(`\s+`)
    normalizedStr := strings.ToLower(re.ReplaceAllString(s, ""))

    // Reverse the normalized string
    reversedStr := reverseString(normalizedStr)

    // Compare the normalized string with the reversed string
    return normalizedStr == reversedStr
}

// Helper function to reverse a string
func reverseString(s string) string {
    runes := []rune(s)
    for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
        runes[i], runes[j] = runes[j], runes[i]
    }
    return string(runes)
}

func main() {
    fmt.Printf("Is palindrome: %v\n", isPalindrome("A man a plan a canal Panama"))
    fmt.Printf("Is palindrome: %v\n", isPalindrome("abcDefg"))
}


 
/*
run:

Is palindrome: true
Is palindrome: false
 
*/

 



answered May 16, 2025 by avibootz
...