Bài tập Rust
Palindrome Check in Rust
Does the text read the same in both directions? Ignore spaces, punctuation and case.
Bạn sẽ học được gì
- 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.
Những điểm quan trọng
- Keep only letters and digits.
- Compare in lower case.
- eq compares two iterators item by item.
Ví dụ Rust chạy được
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" -> 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.
- Chuỗi Palindrome Kiểm tra xem văn bản có đọc xuôi và ngược giống nhau hay không. Dễ
- Số Palindrome Kiểm tra xem một số có đọc xuôi và ngược giống nhau không. Dễ