Exercícios de Go

Anagram Check in Go

Do two texts use exactly the same letters? Sort the letters of both and compare.

  • Iniciante
  • 3 min de leitura
  • 1 exemplo executável
O que você vai aprender
  • 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.

Pontos-chave

  1. Lower case and drop the spaces.
  2. Sort the letters of each text.
  3. Equal sorted forms mean an anagram.

Exemplo executável de Go

Go
Executar código →
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"))
}
Gerar um botão Run para este exemplo Resultado da execução
true
true
false

Pratique

Abra o exemplo no compilador online, mude um valor ou adicione uma linha e tente prever a saída antes de executar. Depois quebre o código de propósito e leia a mensagem do compilador.

Terminou esta lição?

Marque como aprendida para acompanhar seu progresso.

Pratique com um desafio

Use o conteúdo desta lição para resolver um problema real. Cada desafio roda no navegador, com testes instantâneos e uma revisão por IA.

Todos os desafios