Bài tập Go
Anagram Check in Go
Do two texts use exactly the same letters? Sort the letters of both and compare.
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
- Lower case and drop the spaces.
- Sort the letters of each text.
- Equal sorted forms mean an anagram.
Ví dụ Go chạy được
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
falseLuyệ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.
Tiến độ của bạn đang được lưu trong trình duyệt này Đăng nhập để giữ tiến độ trên mọi thiết bị.
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