-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy path1.first-non-repeating-letter-solution.go
More file actions
109 lines (89 loc) · 1.59 KB
/
1.first-non-repeating-letter-solution.go
File metadata and controls
109 lines (89 loc) · 1.59 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"fmt"
)
type Queue []interface{}
func CreateQueue() *Queue {
return &Queue{}
}
func (q *Queue) isEmpty() bool {
return len(*q) == 0
}
func (q *Queue) push(item interface{}) {
*q = append(*q, item)
}
func (q *Queue) pop() (interface{}, bool) {
if q.isEmpty() {
return nil, false
} else {
ele := (*q)[0]
*q = (*q)[1:]
return ele, true
}
}
func (q *Queue) popAtIndex(index int) bool {
if q.isEmpty() {
return false
} else {
*q = append((*q)[:index], (*q)[index+1:]...)
return true
}
}
func (q *Queue) peek() (interface{}, bool) {
if q.isEmpty() {
return nil, false
} else {
return (*q)[0], true
}
}
func linearSearch(arr []interface{}, item string) int {
for i, v := range arr {
if item == v {
return i
}
}
return -1
}
func firstNonRepeatingLetter(str string) []string {
q := CreateQueue()
var res []string
if len(str) == 0 {
return res
}
m := make(map[string]int)
for _, v := range str {
_, ok := m[string(v)]
if ok {
index := linearSearch(*q, string(v))
if index != -1 {
q.popAtIndex(index)
}
if q.isEmpty() {
res = append(res, "-1")
} else {
ele, _ := q.peek()
res = append(res, ele.(string))
}
} else {
m[string(v)] = 1
if q.isEmpty() {
res = append(res, string(v))
} else {
ele, _ := q.peek()
res = append(res, ele.(string))
}
q.push(string(v))
}
}
return res
}
func main() {
var str string
fmt.Print("Enter the string ")
_, _ = fmt.Scan(&str)
result := firstNonRepeatingLetter(str)
for _, v := range result {
fmt.Printf("%s ", string(v))
}
fmt.Println()
}