แบบฝึกหัด Go
Anagram Check in Go
Do two texts use exactly the same letters? Sort the letters of both and compare.
สิ่งที่คุณจะได้เรียนรู้
- 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.
ประเด็นสำคัญ
- Lower case and drop the spaces.
- Sort the letters of each text.
- Equal sorted forms mean an anagram.
ตัวอย่าง 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
โจทย์ทั้งหมด