Упражнения по Rust

Palindrome Check in Rust

Does the text read the same in both directions? Ignore spaces, punctuation and case.

  • Начальный
  • Чтение: 2 мин
  • Примеров для запуска: 1
Что вы узнаете
  • Filtering letters
  • Lower case
  • Comparing with the reverse
level
l0
e1
v2
e3
l4
The first and last letters match, then the next pair.

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.

Главное

  1. Keep only letters and digits.
  2. Compare in lower case.
  3. 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

Практика

Откройте пример в онлайн-компиляторе, измените значение или добавьте строку и попробуйте предсказать вывод до запуска. Затем намеренно сломайте код и прочитайте сообщение компилятора.

Закончили этот урок?

Отметьте его как изученный, чтобы следить за прогрессом.

Далее: Word Frequency Counter →

Попрактикуйтесь на задаче

Примените материал этого урока к реальной задаче. Каждая задача запускается в браузере, с мгновенными тестами и разбором от ИИ.

Все задачи