How do I compare a vector against a reversed version of itself?

前端 未结 2 855
情歌与酒
情歌与酒 2021-01-14 03:16

Why won\'t this compile?

fn isPalindrome(v: Vec) -> bool {
  return v.reverse() == v;
}

I get



        
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-14 03:45

    Since you only need to look at the front half and back half, you can use the DoubleEndedIterator trait (methods .next() and .next_back()) to look at pairs of front and back elements this way:

    /// Determine if an iterable equals itself reversed
    fn is_palindrome(iterable: I) -> bool
    where
        I: IntoIterator,
        I::Item: PartialEq,
        I::IntoIter: DoubleEndedIterator,
    {
        let mut iter = iterable.into_iter();
        while let (Some(front), Some(back)) = (iter.next(), iter.next_back()) {
            if front != back {
                return false;
            }
        }
    
        true
    }
    

    (run in playground)

    This version is a bit more general, since it supports any iterable that is double ended, for example slice and chars iterators.

    It only examines each element once, and it automatically skips the remaining middle element if the iterator was of odd length.

提交回复
热议问题