forked from mrekucci/epi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reversewords.go
33 lines (28 loc) · 938 Bytes
/
reversewords.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
// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.
package strings
// reverseBytes reverse elements of a[s:e] in a.
func reverseBytes(a []byte, s, e int) {
for e > s {
a[s], a[e] = a[e], a[s]
s++
e--
}
}
// ReverseWords returns a new string containing the words from s in reverse order.
// Note: this implementation works only for ASCII table characters.
// The time complexity is O(n) and O(n) additional space is needed.
func ReverseWords(s string) string {
r := []byte(s)
reverseBytes(r, 0, len(s)-1) // Reverse whole sentence.
p := 0
for q := p; q < len(r); q++ { // Reverse each world in the reversed sentence.
if r[q] == ' ' {
reverseBytes(r, p, q-1) // q-1 exclude the ' ' character from reversal.
p = q + 1
}
}
reverseBytes(r, p, len(r)-1) // Reverse the last word.
return string(r)
}