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.
Table of Contents
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.