Ejercicios de Go
Palindrome Check in Go
Does the text read the same in both directions? Ignore spaces, punctuation and case.
Lo que aprenderás
- Filtering letters
- Lower case
- Comparing from both ends
level
l0
e1
v2
e3
l4
The same forwards and backwards
A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.
The first loop keeps only letters and digits in lower case. The second compares the first character with the last, the second with the second to last, and so on, and stops at the first difference. %q prints the text with quotes.
Puntos clave
- Keep only letters and digits.
- Compare in lower case.
- Stop at the first difference.
Ejemplo ejecutable de Go
main.go
package main
import (
"fmt"
"strings"
"unicode"
)
func isPalindrome(text string) bool {
letters := []rune{}
for _, r := range strings.ToLower(text) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
letters = append(letters, r)
}
}
for i, j := 0, len(letters)-1; i < j; i, j = i+1, j-1 {
if letters[i] != letters[j] {
return false
}
}
return true
}
func main() {
for _, text := range []string{"level", "A man, a plan, a canal: Panama", "Go"} {
fmt.Printf("%q -> %t\n", text, isPalindrome(text))
}
}
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Go" -> falsePractica
Abre el ejemplo en el compilador online, cambia un valor o añade una línea y predice la salida antes de ejecutarlo. Después rompe el código a propósito y lee el mensaje del compilador.
¿Terminaste esta lección?
Márcala como aprendida para seguir tu progreso.
Tu progreso está guardado en este navegador Inicia sesión para conservarlo en todos tus dispositivos.
Practica con un reto
Usa lo que cubre esta lección para resolver un problema real. Cada reto se ejecuta en el navegador, con pruebas al instante y una revisión de IA.
- Cadena Palíndroma Verifica si un texto se lee igual de izquierda a derecha y de derecha a izquierda. Fácil
- Número Palíndromo Verifica si un número se lee igual al derecho y al revés. Fácil