-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
45 lines (42 loc) · 792 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"strings"
)
// Input: "Let's take LeetCode contest"
// Output: "s'teL ekat edoCteeL tsetnoc"
func reverseWords(s string) string {
words, start, end := []rune(s), 0, -1
for i, r := range words {
if r == ' ' {
for start < end {
words[start], words[end] = words[end], words[start]
start++
end--
}
start, end = i+1, i
} else {
end++
}
}
for start < end {
words[start], words[end] = words[end], words[start]
start++
end--
}
return string(words)
}
func reverseWords2(s string) string {
var words strings.Builder
var word string
for _, r := range s {
if r != ' ' {
word = string(r) + word
} else {
words.WriteString(word)
words.WriteString(" ")
word = ""
}
}
words.WriteString(word)
return words.String()
}