แบบฝึกหัด Go
Palindrome Check in Go
Does the text read the same in both directions? Ignore spaces, punctuation and case.
สิ่งที่คุณจะได้เรียนรู้
- Filtering letters
- Lower case
- Comparing from both ends
level
l0
e1
v2
e3
l4
The same forwards and backwards
A palindrome reads the same in both directions, such as level. A good check ignores spaces, punctuation and the difference between upper and lower case.
The first loop keeps only letters and digits in lower case. The second compares the first character with the last, the second with the second to last, and so on, and stops at the first difference. %q prints the text with quotes.
ประเด็นสำคัญ
- Keep only letters and digits.
- Compare in lower case.
- Stop at the first difference.
ตัวอย่าง Go ที่รันได้
main.go
package main
import (
"fmt"
"strings"
"unicode"
)
func isPalindrome(text string) bool {
letters := []rune{}
for _, r := range strings.ToLower(text) {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
letters = append(letters, r)
}
}
for i, j := 0, len(letters)-1; i < j; i, j = i+1, j-1 {
if letters[i] != letters[j] {
return false
}
}
return true
}
func main() {
for _, text := range []string{"level", "A man, a plan, a canal: Panama", "Go"} {
fmt.Printf("%q -> %t\n", text, isPalindrome(text))
}
}
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Go" -> falseฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- สตริงพาลินโดรม ตรวจสอบว่าข้อความอ่านเหมือนกันทั้งจากซ้ายไปขวาและขวาไปซ้ายหรือไม่ ง่าย
- ตัวเลขพาลินโดรม ตรวจสอบว่าตัวเลขอ่านเหมือนกันจากซ้ายไปขวาและขวาไปซ้ายหรือไม่ ง่าย