Given a string s consisting of words separated by spaces, find the length of the longest word and return all words that have that maximum length.
Return the words in the order they appear in the original string.
Function Signature
def longest_words(s: str) -> list[str]:
Rules
-
A word is a maximal run of letters between spaces.
-
If a word of maximum length appears more than once, it is included once for each occurrence, at each position where it appears.
-
The returned list is never empty, because
s
contains at least one word.
Constraints
-
1 <= len(s) <= 10^4
-
s
contains only lowercase English letters and spaces.
-
There is at least one word in
s
.
-
Words are separated by single spaces with no leading or trailing spaces.
Examples
Input: s = "the quick brown fox jumps over the lazy dog"
Output: ["quick", "brown", "jumps"]
The maximum word length is 5, reached by "quick", "brown" and "jumps". They are listed in the order they appear in the sentence.
Input: s = "i love programming and algorithms"
Output: ["programming"]
"programming" has 11 letters and "algorithms" has 10, so only "programming" reaches the maximum.
Input: s = "tick tock tick"
Output: ["tick", "tock", "tick"]
All three words have length 4. "tick" appears twice, so it is returned twice, in both of its positions.