Go 연습 문제

Anagram Check in Go

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

  • 초급
  • 3분 분량
  • 실행 가능한 예제 1개
배울 내용
  • 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.

핵심 포인트

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

실행 가능한 Go 예제

Go
코드 실행 →
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

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지