-
Notifications
You must be signed in to change notification settings - Fork 0
/
3.go
60 lines (49 loc) · 1.12 KB
/
3.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
// https://leetcode.com/problems/longest-common-prefix/
package main
type TrieNode struct {
children map[rune]*TrieNode
isEndOfWord bool
}
func insert(root *TrieNode, key string) {
currentNode := root
for _, char := range key {
if node, ok := currentNode.children[char]; ok {
currentNode = node
} else {
newNode := TrieNode{children: make(map[rune]*TrieNode), isEndOfWord: false}
currentNode.children[char] = &newNode
currentNode = &newNode
}
}
currentNode.isEndOfWord = true
}
func longestCommonPrefix(strs []string) string {
if len(strs) == 0 {
return ""
}
if len(strs) == 1 {
return strs[0]
}
trieHead := &TrieNode{children: make(map[rune]*TrieNode)}
for _, str := range strs {
if str == "" {
return ""
}
insert(trieHead, str)
}
if len(trieHead.children) != 1 {
return ""
}
return getLongestCommonPrefix(trieHead)
}
func getLongestCommonPrefix(head *TrieNode) string {
result := ""
for key, node := range head.children {
result += string(key)
if len(node.children) != 1 || node.isEndOfWord {
break
}
return result + getLongestCommonPrefix(node)
}
return result
}