Esercizi di Go
Anagram Check in Go
Do two texts use exactly the same letters? Sort the letters of both and compare.
Cosa imparerai
- Normalizing text
- slices.Sort on runes
- Comparing the results
listen and silent
listen
- sorted
- eilnst
silent
- sorted
- eilnst
Same letters, different order
Two words are anagrams when one can be made by rearranging the letters of the other, such as listen and silent. Sorting the letters of both gives the same result exactly when they are anagrams.
normalize makes the text lower case, drops the spaces and sorts the remaining characters with slices.Sort. Two texts are anagrams when their normalized forms are equal.
Punti chiave
- Lower case and drop the spaces.
- Sort the letters of each text.
- Equal sorted forms mean an anagram.
Esempio Go eseguibile
main.go
package main
import (
"fmt"
"slices"
"strings"
)
func normalize(text string) string {
runes := []rune{}
for _, r := range strings.ToLower(text) {
if r != ' ' {
runes = append(runes, r)
}
}
slices.Sort(runes)
return string(runes)
}
func isAnagram(a, b string) bool {
return normalize(a) == normalize(b)
}
func main() {
fmt.Println(isAnagram("listen", "silent"))
fmt.Println(isAnagram("Dormitory", "dirty room"))
fmt.Println(isAnagram("gopher", "golang"))
}
true
true
falseEsercitati
Apri l'esempio nel compilatore online, cambia un valore o aggiungi una riga e prova a prevedere l'output prima di eseguirlo. Poi rompi il codice di proposito e leggi il messaggio del compilatore.
Hai finito questa lezione?
Segnala come imparata per tenere traccia dei tuoi progressi.
I tuoi progressi sono salvati in questo browser Accedi per conservarli su ogni dispositivo.
Esercitati con una sfida
Usa ciò che questa lezione spiega per risolvere un problema reale. Ogni sfida gira nel browser, con test immediati e una revisione dell'IA.
Tutte le sfide