Search~10 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-434traversal
You work on the search box of an app. People type or paste queries, and the text often has stray spaces: before the first word, after the last, and several in a row.
Your team lead says: "The search service charges by the number of words in a query. Count the words, whatever the spaces look like."
A word is a run of letters. Spaces separate words, and any number of spaces counts as one separator.
Write count_words(query).
query holds lower-case letters and spaces.query.Input: query = " buy red shoes "
Output: 3Words start at the letters in this table, where the character before is a space or the text begins.
| Position | Letter | Words so far |
|---|---|---|
| 2 | b |
1 |
| 8 | r |
2 |
| 12 | s |
3 |
The query has 3 words.
Input: query = ""
Output: 0An empty query has no words.
Input: query = " "
Output: 0Spaces alone make no word.
0 ≤ query.length ≤ 1,000,000 (characters)query holds only the letters a to z and the space characterCutting the text word by word copies the rest of it each time. With 1,000,000 characters of single letters that is about 2.5 × 10^11 copied characters. One pass over the text makes 1,000,000 steps, which fits easily.