go: add «1408. String Matching in an Array»
URL: https://leetcode.com/problems/string-matching-in-an-array/ Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
d2669c3687
commit
6dfd741e6a
1 changed files with 54 additions and 0 deletions
54
go/string-matching-in-an-array.go
Normal file
54
go/string-matching-in-an-array.go
Normal file
|
@ -0,0 +1,54 @@
|
|||
package main
|
||||
|
||||
type TrieNode struct {
|
||||
frequency int
|
||||
children map[rune]*TrieNode
|
||||
}
|
||||
|
||||
func NewNode() *TrieNode {
|
||||
return &TrieNode{
|
||||
frequency: 0,
|
||||
children: make(map[rune]*TrieNode),
|
||||
}
|
||||
}
|
||||
|
||||
func (node *TrieNode) Insert(word string) {
|
||||
n := node
|
||||
for _, c := range word {
|
||||
_, ok := n.children[c]
|
||||
if !ok {
|
||||
n.children[c] = NewNode()
|
||||
}
|
||||
|
||||
n = n.children[c]
|
||||
n.frequency++
|
||||
}
|
||||
}
|
||||
|
||||
func (node *TrieNode) IsSubstring(word string) bool {
|
||||
n := node
|
||||
for _, c := range word {
|
||||
n = n.children[c]
|
||||
}
|
||||
|
||||
return n.frequency > 1
|
||||
}
|
||||
|
||||
func stringMatching(words []string) []string {
|
||||
matching := make([]string, 0)
|
||||
|
||||
root := NewNode()
|
||||
for _, word := range words {
|
||||
for start := 0; start < len(word); start++ {
|
||||
root.Insert(word[start:])
|
||||
}
|
||||
}
|
||||
|
||||
for _, word := range words {
|
||||
if root.IsSubstring(word) {
|
||||
matching = append(matching, word)
|
||||
}
|
||||
}
|
||||
|
||||
return matching
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue