MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / reverseWords

Function reverseWords

reverse_words_in_a_string_151/solution.go:6–33  ·  view source on GitHub ↗

Note: solution using a single string with which tokens are prepended into.

(s string)

Source from the content-addressed store, hash-verified

4
5// Note: solution using a single string with which tokens are prepended into.
6func 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.

Callers 1

Test_reverseWordsFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_reverseWordsFunction · 0.68