forked from hoanhan101/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_string_test.go
65 lines (52 loc) · 1.35 KB
/
reverse_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
/*
Problem:
- Given a list of string, reverse its order in place.
Example:
- Input: []string{"a", "b", "c", "d"}
Output: []string{"d", "c", "b", "a"}
Approach:
- Use two pointers approach to swap two values on both ends as we move toward
the middle.
Solution:
- Initialize the two pointers, one starts at the beginning and one starts at
the end of the list.
- While the start pointer does not meet the end pointer in the middle, keep
swapping these two values.
- Move the start pointer up and move the end pointer down.
Cost:
- O(n) time, O(1) space.
*/
package interviewcake
import (
"testing"
"github.com/hoanhan101/algo/common"
)
func TestReverseString(t *testing.T) {
tests := []struct {
in []string
expected []string
}{
{[]string{}, []string{}},
{[]string{"a"}, []string{"a"}},
{[]string{"a", "b"}, []string{"b", "a"}},
{[]string{"a", "b", "c"}, []string{"c", "b", "a"}},
{[]string{"a", "b", "c", "d"}, []string{"d", "c", "b", "a"}},
}
for _, tt := range tests {
result := reverseString(tt.in)
common.Equal(t, tt.expected, result)
}
}
func reverseString(list []string) []string {
// initialize start and end index pointer.
start := 0
end := len(list) - 1
for start < end {
// swap 2 character using a temp variable.
common.Swap(list, start, end)
// move the cursor toward the middle.
start++
end--
}
return list
}