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 のレビューも受けられます。
すべてのチャレンジ