648.replace-words.go 708 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. type trie struct {
  2. word bool
  3. next [26]*trie
  4. }
  5. func (t *trie) insert(s string) {
  6. for _, r := range s {
  7. i := r - 'a'
  8. if t.next[i] == nil {
  9. t.next[i] = &trie{}
  10. }
  11. t = t.next[i]
  12. }
  13. t.word = true
  14. }
  15. func (t *trie) search(s string) string {
  16. var sb strings.Builder
  17. for _, r := range s {
  18. t = t.next[r-'a']
  19. if t == nil {
  20. return ""
  21. }
  22. sb.WriteRune(r)
  23. if t.word {
  24. break
  25. }
  26. }
  27. return sb.String()
  28. }
  29. func replaceWords(dict []string, sentence string) string {
  30. var t trie
  31. for i := range dict {
  32. t.insert(dict[i])
  33. }
  34. words := strings.Split(sentence, " ")
  35. for i := range words {
  36. if root := t.search(words[i]); root != "" {
  37. words[i] = root
  38. }
  39. }
  40. return strings.Join(words, " ")
  41. }