description

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

 

Example 1:

Input: strs = ["flower","flow","flight"]
Output: "fl"

Example 2:

Input: strs = ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.

 

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters if it is non-empty.

submission

impl Solution {
    pub fn longest_common_prefix(strs: Vec<String>) -> String {
        // convert them to iterators and save them here for reference
        let mut iters: Vec<_> = strs.iter().map(|s| s.chars()).collect();
        std::iter::from_fn(|| {
            iters
                .iter_mut()
                // get one char from each iterator
                .map(|mut iter| iter.next())
                // we use Option<Option<char>> to fold
                // the outer Option checks any failure
                // the inner Option is for initial value
                // clippy will suggest us to use try_fold
                // however here fold is probably more clear
                .fold(Some(None), |init, ch| match (init, ch) {
                    // the letter from the first string
                    (Some(None), Some(ch)) => Some(Some(ch)),
                    // from other string, check equality
                    (Some(Some(c)), Some(ch)) if c == ch => Some(Some(ch)),
                    _ => None,
                })
                .flatten()
        })
        .collect()
    }
}