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:
Matej Focko 2025-01-07 23:41:26 +01:00
parent d2669c3687
commit 6dfd741e6a
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View 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
}