-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy path01_is_unique.go
51 lines (42 loc) · 1.03 KB
/
01_is_unique.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
package ch01
import "strings"
// IsUnique determine if a string has all unique chars
// This solution is based on HashTable (Go map) data structure
func IsUnique(s string) bool {
set := make(map[rune]bool)
for _, c := range s {
if _, ok := set[c]; ok {
return false
}
set[c] = true
}
return true
}
// IsUniqueVanilla determine if a string has all unique chars
// This solution doesn't utilize any additional data structures
func IsUniqueVanilla(s string) bool {
lens := len(s)
for i := 0; i < lens; i++ {
for j := i + 1; j < lens; j++ {
if s[i] == s[j] {
return false
}
}
}
return true
}
// IsUniqueBits determines if a string has all unique chars (only works for ASCII)
// This solution doesn't utilize any additional data structures and has O(n) time complexity
func IsUniqueBits(s string) bool {
s = strings.ToLower(s)
var vector int32
for _, rune := range s {
index := rune - 'a'
mask := int32(1 << index)
if (vector & mask) == mask {
return false
}
vector = vector | mask
}
return true
}