-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution387.go
67 lines (61 loc) · 1.35 KB
/
solution387.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
package solution387
// ============================================================================
// 387. First Unique Character in a String
// URL: https://leetcode.com/problems/first-unique-character-in-a-string/
// ============================================================================
/*
$ go test -bench=. -benchmem
goos: linux
goarch: amd64
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_firstUniqChars-24 466539740 6.450 ns/op 0 B/op 0 allocs/op
Benchmark_firstUniqChars_first_approach-24 2505699 478.0 ns/op 48 B/op 2 allocs/op
PASS
*/
func firstUniqChar(s string) int {
repeat := false
for i := 0; i < len(s); i++ {
repeat = false
for j := 0; j < len(s); j++ {
if i != j && s[i] == s[j] {
repeat = true
break
}
}
if !repeat {
return i
}
}
return -1
}
func firstUniqChar_first_approach(s string) int {
m1 := make(map[byte]int)
m2 := make(map[byte]int)
for i := 0; i < len(s); i++ {
ch1 := byte(s[i])
_, ok := m1[ch1]
if !ok {
m1[ch1] = 1
m2[ch1] = i
} else {
m1[ch1]++
}
if m1[ch1] >= 2 {
m2[ch1] = -1
}
}
var mval int = 1<<63 - 1
var found bool = false
for k, v := range m1 {
if v == 1 && m2[k] != -1 {
if m2[k] < mval {
mval = m2[k]
found = true
}
}
}
if found {
return mval
}
return -1
}