แบบฝึกหัด Rust
Palindrome Check in Rust
Does the text read the same in both directions? Ignore spaces, punctuation and case.
สิ่งที่คุณจะได้เรียนรู้
- Filtering letters
- Lower case
- Comparing with the reverse
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.
filter keeps only letters and digits and map makes them lower case. eq compares the letters with the same letters in reverse order, without building a second vector. {text:?} prints the text with quotes.
ประเด็นสำคัญ
- Keep only letters and digits.
- Compare in lower case.
- eq compares two iterators item by item.
ตัวอย่าง Rust ที่รันได้
Rust
main.rs
fn is_palindrome(text: &str) -> bool {
let letters: Vec<char> = text
.chars()
.filter(|c| c.is_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect();
letters.iter().eq(letters.iter().rev())
}
fn main() {
for text in ["level", "A man, a plan, a canal: Panama", "Rust"] {
println!("{text:?} -> {}", is_palindrome(text));
}
}
"level" -> true
"A man, a plan, a canal: Panama" -> true
"Rust" -> falseฝึกฝน
เปิดตัวอย่างในคอมไพเลอร์ออนไลน์ ลองเปลี่ยนค่าหรือเพิ่มบรรทัด แล้วทายผลลัพธ์ก่อนกดรัน จากนั้นลองทำให้โค้ดผิดโดยตั้งใจ แล้วอ่านข้อความจากคอมไพเลอร์
เรียนบทนี้จบแล้วใช่ไหม
ทำเครื่องหมายว่าเรียนแล้วเพื่อติดตามความคืบหน้า
ความคืบหน้าของคุณถูกบันทึกไว้ในเบราว์เซอร์นี้ เข้าสู่ระบบเพื่อเก็บไว้ใช้ได้ทุกอุปกรณ์
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- สตริงพาลินโดรม ตรวจสอบว่าข้อความอ่านเหมือนกันทั้งจากซ้ายไปขวาและขวาไปซ้ายหรือไม่ ง่าย
- ตัวเลขพาลินโดรม ตรวจสอบว่าตัวเลขอ่านเหมือนกันจากซ้ายไปขวาและขวาไปซ้ายหรือไม่ ง่าย