Note: solution using a single string with which tokens are prepended into.
(s string)
| 4 | |
| 5 | // Note: solution using a single string with which tokens are prepended into. |
| 6 | func reverseWords(s string) string { |
| 7 | s = strings.Trim(s, " ") |
| 8 | |
| 9 | sFinal := "" |
| 10 | start := 0 |
| 11 | finish := 0 |
| 12 | for finish < len(s) { |
| 13 | if string(s[finish]) == " " { |
| 14 | // prepend the token found into the final string |
| 15 | // this is slow, "don't concat strings in a loop" |
| 16 | sFinal = s[start:finish] + " " + sFinal |
| 17 | |
| 18 | // clear whitespace in between tokens for next start |
| 19 | for string(s[finish]) == " " { |
| 20 | finish++ |
| 21 | } |
| 22 | |
| 23 | start = finish |
| 24 | } else { |
| 25 | finish++ |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | // Prepend final token as finish stopped at the end of s |
| 30 | sFinal = s[start:finish] + " " + sFinal |
| 31 | |
| 32 | return strings.TrimSuffix(sFinal, " ") |
| 33 | } |
| 34 | |
| 35 | // Note: First, correct, and optimal runtime solution using an array |
| 36 | // for tokens and reversing the array. |
no outgoing calls