Problem overview
The function longest_word receives a vector of strings, words, and returns the word with the most letters. If several words share the longest length, the first of them is the answer. The vector always has at least one word.
For ["I", "love", "pancakes"] the answer is "pancakes", with 8 letters. For ["apple", "kiwi", "mango"], "apple" and "mango" both have 5 letters, and "apple" comes first, so it wins.
Approach: keep the best so far
Scan the words once and remember the longest word seen up to now. Before the scan, the first word is the best candidate there is. Each later word either beats it or doesn't. When the scan ends, every word has had its chance, so the remembered word is the longest.
The tie rule comes from the comparison. If a word replaces the best only when it is strictly longer, an equal-length word never takes over, and the earliest of the longest words stays.
Step by step
- Start with the first word.
words[0].clone()goes into a mutable variable,longest. The vector is never empty, so index 0 exists. - Loop over
&words. Eachwordis a borrowed reference to a string. - Compare lengths with
>. The testword.len() > longest.len()is strict, which keeps the first word on a tie. - Replace the best with a copy of the word.
- Return
longestafter the loop.
The solution in Rust
impl Solution {
fn longest_word(words: Vec<String>) -> String {
let mut longest = words[0].clone();
for word in &words {
if word.len() > longest.len() {
longest = word.clone();
}
}
return longest;
}
}
The Rust details worth a closer look:
- Why
clone().words[0]can't be moved out of the vector by indexing, because that would leave a hole in it.clone()makes an independent copy of theString, solongestowns its text. The same applies tolongest = word.clone(), wherewordis only a reference. - Reassignment. Assigning to
longestdrops the string it held before. That is why the variable is declared withlet mut. - Comparing lengths, not strings.
len()returns ausize. Comparing the strings themselves with>would order them alphabetically, which is a different question. - The first word is compared with itself. The loop starts at the first word, which is already
longest. That comparison is false and harmless. - Indexing panics on an empty vector.
words[0]on an empty vector stops the program, which is why the lesson guarantees at least one word.
Tracing a tie
Take ["apple", "kiwi", "mango"]. longest starts as "apple" (5). "apple" is not longer than itself, so nothing changes. "kiwi" has 4 letters, which is not more than 5. "mango" has 5, which is not more than 5, so it doesn't replace "apple". The loop ends and "apple" is returned. A strict comparison is the entire tie rule; no extra code is needed.
Another way to get the same answer is words.iter().max_by_key(|w| w.len()), but it returns the last maximum on a tie, so it would give "mango" here. Writing the loop by hand keeps control of the tie rule.
Edge cases and common mistakes
- Using
>=. The last of the longest words would win.["mango", "apple"]would then return "apple" instead of "mango". - Starting from an empty string. That works for non-empty words, but starting from the first word is clearer and also covers a single-word vector.
- One word.
["code"]returns"code"without any replacement. - Returning the length. The function returns the word, a
String, not its length.
Testing
["I", "love", "pancakes"]gives"pancakes".["apple", "kiwi", "mango"]gives"apple".["mango", "apple"]gives"mango".["code"]gives"code".
