#Is this a good solution for a palindrome algorithm?

7 messages · Page 1 of 1 (latest)

slow monolith
#

Hi everyone! I implemented a palindrome function where I use iter.next() and iter.next_back() to navigate the string so that I don't loop over it twice.
I'm not sure about the loop part, I think it could be written in a much simpler/clearer way

fn is_palindrome (str: &str) -> bool {
    if str.len() < 3 {
        return false
    }

    let binding = str
        .replace(&['(', ')', ',', '-', '–', '\"', '.', ';', ' ', ':', '\''][..], "")
        .to_lowercase();
    let trimmed_str = binding.trim();
    let iter_bytes = trimmed_str.trim().as_bytes().iter();

    match IntoIterator::into_iter(iter_bytes) {
        mut iter => loop {
            let next: &u8;
            let back:&u8;

            match iter.next() {
                Some(val) => next = val,
                None => break,
            }

            match iter.next_back() {
                Some(val) => back = val,
                None => break,
            }

            if back != next {
                return false
            }
        },
    };
    return true;
}
whole pumice
#

for a palindrome function this is doing too much and has too many unnecessary restrictions

#

here would be my implementation

#

?play

fn is_palindrome(s: &str) -> bool {
    s.chars().eq(s.chars().rev())
}

fn main() {
    dbg!(is_palindrome("asdf"));
    dbg!(is_palindrome("racecar"));
} 
dreamy prismBOT
#
[src/main.rs:6] is_palindrome("asdf") = false
[src/main.rs:7] is_palindrome("racecar") = true```
vivid delta
#

specifically regarding the loop part:

  • You don't need to call IntoIterator::into_iter: iter_bytes is already an Iterator
  • That match with an irrefutable pattern is kinda unusual, not really a pattern you should strive for: you can simply use let instead
  • You could simplify the whole loop with something like
while let (Some(left), Some(right)) = (iter_bytes.next(), iter_bytes.next_back()) {
    if left != right {
        return false
    }
}
slow monolith
#

Thank you all!
I didn't know about while let, thank you!