Bài tập Go

Anagram Check in Go

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

  • Cơ bản
  • Đọc trong 3 phút
  • 1 ví dụ chạy được
Bạn sẽ học được gì
  • 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.

Những điểm quan trọng

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

Ví dụ Go chạy được

Go
Chạy code →
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"))
}
Lấy nút Run cho ví dụ này Kết quả khi chạy
true
true
false

Luyện tập

Mở ví dụ trong trình biên dịch online, đổi một giá trị hoặc thêm một dòng, rồi đoán kết quả trước khi chạy. Sau đó cố ý làm code bị lỗi và đọc thông báo của trình biên dịch.

Bạn học xong bài này chưa?

Đánh dấu đã học để theo dõi tiến độ của bạn.

Luyện tập với thử thách

Áp dụng kiến thức của bài học này để giải một bài toán thực tế. Mỗi thử thách chạy ngay trên trình duyệt, có kiểm thử tức thì và AI nhận xét.

Tất cả thử thách