Published on

Palindrome string

Authors

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 take an example string racecar:

  • “racecar” is a palindrome, because its last two characters are the same.
  • simple check is if we reverse string the result is still same
  • so we just loop string, then compare string from first index (s[i]) and last index (s[len(s)-1-i]) until reach the middle position

Here the sample implementation

main.go

_20
package main
_20
_20
import "fmt"
_20
_20
func isPalindrome(s string) bool {
_20
// to ignore case, string converted to lower case
_20
s = strings.ToLower(s)
_20
_20
for i := 0; i < len(s)/2; i++ {
_20
if s[i] != s[len(s)-1-i] {
_20
return false
_20
}
_20
}
_20
return true
_20
}
_20
_20
func main() {
_20
fmt.Println(isPalindrome("racecar")) // prints true
_20
fmt.Println(isPalindrome("hello")) // prints false
_20
}