Created
February 12, 2019 07:09
-
-
Save osdrv/f84f37d0a05f57b9c363c7a796481e38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type TrieNode struct { | |
pool map[rune]*TrieNode | |
} | |
func NewTrieNode() *TrieNode { | |
return &TrieNode{pool: make(map[rune]*TrieNode)} | |
} | |
func (t *TrieNode) Insert(word string) { | |
ptr := t | |
for _, ch := range word { | |
if _, ok := ptr.pool[ch]; !ok { | |
ptr.pool[ch] = NewTrieNode() | |
} | |
ptr = ptr.pool[ch] | |
} | |
ptr.pool[0] = nil | |
} | |
type QueueItem struct { | |
ptr *TrieNode | |
offset int | |
acc []int | |
} | |
func wordBreak(s string, wordDict []string) []string { | |
t := NewTrieNode() | |
for _, word := range wordDict { | |
t.Insert(word) | |
} | |
ix := [][]int{} | |
q := make([]QueueItem, 0, len(s)) | |
q = append(q, QueueItem{t, 0, []int{}}) | |
var head QueueItem | |
for len(q) > 0 { | |
head, q = q[0], q[1:] | |
if head.offset == len(s) { | |
if _, ok := head.ptr.pool[0]; ok { | |
ix = append(ix, head.acc) | |
} | |
continue | |
} | |
if _, ok := head.ptr.pool[0]; ok { | |
q = append(q, QueueItem{ | |
ptr: t, | |
offset: head.offset, | |
acc: append(head.acc, head.offset), | |
}) | |
} | |
if next, ok := head.ptr.pool[rune(s[head.offset])]; ok { | |
q = append(q, QueueItem{ | |
ptr: next, | |
offset: head.offset + 1, | |
acc: head.acc, | |
}) | |
} | |
} | |
res := make([]string, 0, len(ix)) | |
for _, ixset := range ix { | |
b := make([]string, 0, len(ixset)+1) | |
prev := 0 | |
for _, off := range ixset { | |
b = append(b, s[prev:off]) | |
prev = off | |
} | |
b = append(b, s[prev:len(s)]) | |
res = append(res, strings.Join(b, " ")) | |
} | |
return res | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment