Palindrome string

0 min read Tweet this post

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

package main

import "fmt"

func isPalindrome(s string) bool {
    // to ignore case, string converted to lower case
    s = strings.ToLower(s)

    for i := 0; i < len(s)/2; i++ {
        if s[i] != s[len(s)-1-i] {
            return false
        }
    }
    return true
}

func main() {
    fmt.Println(isPalindrome("racecar"))  // prints true
    fmt.Println(isPalindrome("hello"))    // prints false
}
go cp