-
Notifications
You must be signed in to change notification settings - Fork 1
/
checkstringunique.go
85 lines (71 loc) · 1.32 KB
/
checkstringunique.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
package main
import (
"fmt"
"sort"
)
func main() {
str := "abca"
fmt.Printf("Given string %#v is unique=%v", str, isStringUnique3(str))
}
// search using existing data structure - map
func isStringUnique1(str string) bool {
m := map[string]string{}
for i := 0; i < len(str); i++ {
key := string(str[i])
val := string(str[i])
if val == m[key] {
return false
}
m[key] = val
}
return true
}
// basic search without existing data structure
func isStringUnique2(str string) bool {
var vArr []string
exists := func(val string, vArr []string) bool {
for i := 0; i < len(vArr); i++ {
if val == vArr[i] {
return true
}
}
return false
}
for i := 0; i < len(str); i++ {
val := string(str[i])
if exists(val, vArr) {
return false
}
vArr = append(vArr, val)
}
return true
}
// based on binary search
func isStringUnique3(str string) bool {
var vArr []string
exists := func(val string, vArr []string) bool {
sort.Strings(vArr)
begin := 0
end := len(vArr)
for begin < end {
mid := (begin + end) / 2
if val == vArr[mid] {
return true
}
if val < vArr[mid] {
end = mid
} else {
begin = mid + 1
}
}
return false
}
for i := 0; i < len(str); i++ {
val := string(str[i])
if exists(val, vArr) {
return false
}
vArr = append(vArr, val)
}
return true
}