7

leetcode 140. 单词拆分 II

 2 years ago
source link: https://iamxcb.com/leetcode-140.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

leetcode 140. 单词拆分 II

发表于 2019-07-05

| 0

| 阅读次数:

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

  • 分隔时可以重复使用字典中的单词。
  • 你可以假设字典中没有重复的单词。
输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
  "cats and dog",
  "cat sand dog"
]
示例 2:
输入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出:
[
  "pine apple pen apple",
  "pineapple pen apple",
  "pine applepen apple"
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出:
[]

记忆化回溯,hash[s] 保存相应字符串 s 对应的单词组合

示例代码(go)

func wordBreak(s string, wordDict []string) []string {
hash := make(map[string][]string)
wordHash := make(map[string]bool)
for _, word := range wordDict {
wordHash[word] = true
}
return dfs(s, wordDict, hash, wordHash)
}

func dfs(s string, wordDict []string, hash map[string][]string, wordHash map[string]bool) []string {
if _, ok := hash[s]; ok {
return hash[s]
}
res := make([]string, 0)
n := len(s)
if n == 0 {
res = append(res, "")
return res
}
for i := 0; i < n; i++ {
if wordHash[s[:i+1]] {
sublist := dfs(s[i+1:], wordDict, hash, wordHash)
for _, sub := range sublist {
space := " "
if sub == "" {
space = ""
}
res = append(res, s[:i+1]+space+sub)
}
}
}
hash[s] = res
return res
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK