Sling Academy
Home/Golang/Detecting Palindromes Using Strings in Go

Detecting Palindromes Using Strings in Go

Last updated: November 24, 2024

In this article, we will explore how to detect palindromes by manipulating strings in the Go programming language. A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization). Let's build a program in Go to check if a given string is a palindrome.

Basic Example

For starters, we will craft a simple function to check if a string is a palindrome by reversing the string and comparing it with the original.

package main

import (
    "fmt"
    "strings"
)

func isPalindrome(s string) bool {
    reversed := ""
    for _, v := range s {
        reversed = string(v) + reversed
    }
    return s == reversed
}

func main() {
    fmt.Println(isPalindrome("madam")) // true
    fmt.Println(isPalindrome("hello")) // false
}

Intermediate Level

Let’s enhance the palindrome checker by ignoring spaces and case sensitivity. This involves cleaning up the input string before checking for palindromes.

package main

import (
    "fmt"
    "strings"
)

func isPalindromeClean(s string) bool {
    s = strings.ToLower(s)
    s = strings.ReplaceAll(s, " ", "")
    reversed := ""
    for _, v := range s {
        reversed = string(v) + reversed
    }
    return s == reversed
}

func main() {
    fmt.Println(isPalindromeClean("A man a plan a canal Panama")) // true
    fmt.Println(isPalindromeClean("Hello")) // false
}

Advanced Approach

For a more complex implementation, we'll directly compare characters from the start and end of the string moving toward the center, allowing for better performance.

package main

import (
    "fmt"
    "unicode"
)

func isPalindromeAdvanced(s string) bool {
    cleaned := ""
    for _, r := range s {
        if unicode.IsLetter(r) || unicode.IsNumber(r) {
            cleaned += string(unicode.ToLower(r))
        }
    }
    n := len(cleaned)
    for i := 0; i < n/2; i++ {
        if cleaned[i] != cleaned[n-1-i] {
            return false
        }
    }
    return true
}

func main() {
    fmt.Println(isPalindromeAdvanced("Was it a car or a cat I saw?")) // true
    fmt.Println(isPalindromeAdvanced("No lemon, no melon")) // true
    fmt.Println(isPalindromeAdvanced("Go Hang a Salami, I'm a Lasagna Hog")) // true
}

Conclusion

In this article, we implemented a simple to advanced palindrome checker in Go that handles spaces and case sensitivity. We also improved it to ignore all non-alphanumeric characters. This demonstrates Go's capabilities for string manipulation and basic algorithm crafting. You can further optimize based on specific use cases or integrate it as a library function in your Go applications.

Next Article: Changing Case: Uppercase, Lowercase, and Title Case in Go

Previous Article: Reversing a String in Go: Methods and Examples

Series: Working with Strings in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant