Palindrome Check Over Runes

Check palindromes by converging two indexes over a rune slice, so multibyte text like CJK phrases is compared per character instead of per byte.

GoData Integrity

Code

gosnippet
20 lines
package main

import "fmt"

// palindrome check over runes: two indexes converge toward the middle
func isPalindrome(s string) bool {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		if runes[i] != runes[j] {
			return false
		}
	}
	return true
}

func main() {
	for _, s := range []string{"level", "上海自来水来自海上", "devexamples"} {
		fmt.Printf("%s -> %v\n", s, isPalindrome(s))
	}
}

Palindrome Check Over Runes: how the code works

Structurally, expect the functions isPalindrome and main and nothing else.

One loop does the cycling here: for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1.

Caveats

  • Pure standard library — paste it in and it works.

Putting it to use

Entry signature: func isPalindrome(s string) bool

Launch the file; main takes over and steps through isPalindrome.

Core lines

for _, s := range []string{"level", "上海自来水来自海上", "devexamples"} {
	fmt.Printf("%s -> %v\n", s, isPalindrome(s))
}
func isPalindrome(s string) bool {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		if runes[i] != runes[j] {
			return false
		}
	}
	return true
}

Interactive Tools for This Topic

FAQ

How do you run Palindrome Check Over Runes?
Nothing to install first — run the file and the program does the rest.