Go-Übungen
Anagram Check in Go
Do two texts use exactly the same letters? Sort the letters of both and compare.
Das lernst du
- 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.
Das Wichtigste
- Lower case and drop the spaces.
- Sort the letters of each text.
- Equal sorted forms mean an anagram.
Ausführbares Go-Beispiel
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
falseÜben
Öffne das Beispiel im Online-Compiler, ändere einen Wert oder füge eine Zeile hinzu und sage die Ausgabe voraus, bevor du es ausführst. Bring den Code danach absichtlich zum Scheitern und lies die Meldung des Compilers.
Lektion fertig?
Markiere sie als gelernt, um deinen Fortschritt zu verfolgen.
Dein Fortschritt ist in diesem Browser gespeichert Melde dich an, um ihn auf jedem Gerät zu behalten.
Mit einer Challenge üben
Nutze den Inhalt dieser Lektion, um ein echtes Problem zu lösen. Jede Challenge läuft im Browser, mit sofortigen Tests und einem KI-Review.
Alle Challenges