-
Notifications
You must be signed in to change notification settings - Fork 1
/
basics.go
87 lines (72 loc) · 1.54 KB
/
basics.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
87
package algorithms
import (
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
}
// Shuffle does a Fisher-Yates shuffle.
//
// Time O(n) | Space O(1)
func Shuffle(slice []int) {
// base case: cannot shuffle empty or 1-element slice
if len(slice) <= 1 {
return
}
for i := len(slice) - 1; i > 0; i-- {
j := rand.Intn(i + 1)
slice[i], slice[j] = slice[j], slice[i]
}
}
// Reverse a slice of int iteratively & in-place.
//
// Time O(n) | Space O(1)
func Reverse(s []int) {
// base case: cannot reverse empty or 1-element slice
if len(s) <= 1 {
return
}
for i := len(s)/2 - 1; i >= 0; i-- {
opp := len(s) - 1 - i
s[i], s[opp] = s[opp], s[i]
}
}
// IsPalindrome returns true if the given string is a palindrome ignoring whitespace,
// punctuation, & case sensitivity.
//
// Time O(n) | Space O(1)
func IsPalindrome(str string) bool {
n := len(str)
// base case: empty and single char string are palindromes
if n == 0 || n == 1 {
return true
}
for i := 0; i < n/2; i++ {
front := str[i]
back := str[n-1]
if front != back {
return false
}
n--
}
return true
}
// IsPalindromeRecursive does the same as IsPalindrome using recursion.
//
// Time O(n) | Space O(1)
func IsPalindromeRecursive(str string) bool {
var recurse func(s string) bool
recurse = func(s string) bool {
n := len(s)
// base case: empty or single char string are palindromes
if n == 0 || n == 1 {
return true
} else if s[0] != s[n-1] {
return false
} else {
return recurse(s[1 : n-1])
}
}
return recurse(str)
}