140.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package main
  2. import (
  3. "strings"
  4. )
  5. func wordBreak(s string, wordDict []string) []string {
  6. resMap := make(map[string][]string)
  7. return wordBreakDFS(s, wordDict, &resMap)
  8. }
  9. func wordBreakDFS(s string, wordDict []string, resMap *map[string][]string) []string {
  10. if _, ok := (*resMap)[s]; ok { // DFS solution is very pratical! Try to remember
  11. return (*resMap)[s]
  12. } // Use a map to limit the search
  13. if len(s) == 0 {
  14. return []string{""}
  15. }
  16. res := make([]string, 0)
  17. for i := range wordDict {
  18. if strings.HasPrefix(s, wordDict[i]) {
  19. sublist := wordBreakDFS(s[len(wordDict[i]):], wordDict, resMap)
  20. for j := range sublist {
  21. var suffix string
  22. if sublist[j] != "" {
  23. suffix = " " + sublist[j]
  24. }
  25. res = append(res, wordDict[i]+suffix)
  26. }
  27. }
  28. }
  29. (*resMap)[s] = res
  30. return res
  31. }
  32. // func main() {
  33. // fmt.Println(wordBreak(
  34. // "catsanddog",
  35. // []string{"cat", "cats", "and", "sand", "dog"}))
  36. // fmt.Println(wordBreak(
  37. // "pineapplepenapple",
  38. // []string{"apple", "pen", "applepen", "pine", "pineapple"}))
  39. // fmt.Println(wordBreak(
  40. // "catsandog",
  41. // []string{"cats", "dog", "sand", "and", "cat"}))
  42. // }