Online store~12 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-151strings
An online store imports product titles from supplier files. The files are messy: titles have extra spaces at the start, at the end and between words.
The store builds a search key from each title with the words in reverse order, so that the last word, often the product type, comes first. The key has one space between words and none at either end. A title can hold up to 1,000,000 characters.
Write reverse_words(title).
title holds the letters a to z and the space character. A word is a maximal block of letters.title has no words, return an empty text.Input: title = " the quick brown fox "
Output: "fox brown quick the"There are four words. They come back in reverse order, with single spaces.
Walk back from the last character. Skip spaces, find each word with two indexes, and append it.
| Word found | Start to end | Builder after |
|---|---|---|
| fox | 21 to 23 | fox |
| brown | 15 to 19 | fox brown |
| quick | 8 to 12 | fox brown quick |
| the | 2 to 4 | fox brown quick the |
The spaces at both ends and the extra spaces between words are skipped, not copied.
Input: title = "single"
Output: "single"One word stays as it is.
Input: title = " "
Output: ""No words make an empty text.
1 ≤ title.length ≤ 1,000,000 (characters in the title)title uses only a to z and the space characterA title can have about 500,000 one-letter words. Cutting the last word off the text again and again copies the rest of the text each time, which is about 2.5 × 10^11 characters. One scan from the end costs about n steps.