-
Notifications
You must be signed in to change notification settings - Fork 376
/
reverse_words_string_test.go
86 lines (70 loc) · 1.85 KB
/
reverse_words_string_test.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
Problem:
- Given a string, reverse it word by word.
Example:
- Input: "hard so be to have not does interview coding"
Output: "coding interview does not have to be so hard"
Approach:
- Approach with a two-pass solution.
- The first pass is to split the string into an array of words separated by
spaces.
- The second pass is to reverse the order of words in the array by using
two-pointer approach: swap two values on both ends as we move toward the
middle.
- Concatenate the values of ordered array to create a final string.
Cost:
- O(n) time, O(n) space.
*/
package leetcode
import (
"strings"
"testing"
"github.com/hoanhan101/algo/common"
)
func TestReverseWordsString(t *testing.T) {
tests := []struct {
in string
expected string
}{
{"", ""},
{"a", "a"},
{" a", "a"},
{"a ", "a"},
{"b a", "a b"},
{"c b a", "a b c"},
{"d c b a", "a b c d"},
{"hard so be to have not does interview coding", "coding interview does not have to be so hard"},
}
for _, tt := range tests {
result := reverseWordsString(tt.in)
common.Equal(t, tt.expected, result)
}
}
func reverseWordsString(in string) string {
// if the input is an empty string, return itself.
if in == "" {
return in
}
// slice input string into a list of words separated by spaces.
words := strings.Split(in, " ")
// clean up leading and trailing space if there is any.
if words[0] == "" {
words = words[1:]
}
if words[len(words)-1] == "" {
words = words[:len(words)-1]
}
// start reversing the order of words by first initializing the start and
// end index pointer.
start := 0
end := len(words) - 1
for start < end {
// swap 2 character using a temp variable.
common.SwapString(words, start, end)
// move the cursor toward the middle.
start++
end--
}
// return the concatenated string created from words.
return strings.Join(words, " ")
}