Skip to content
This repository was archived by the owner on Sep 20, 2023. It is now read-only.

Commit c4231c0

Browse files
aQuaaQua
aQua
authored and
aQua
committed
472 finish
1 parent c66479d commit c4231c0

File tree

3 files changed

+15
-12
lines changed

3 files changed

+15
-12
lines changed
67.5 KB
Loading

Algorithms/0472.concatenated-words/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,5 @@ Note:
2626
## 解题思路
2727

2828
见程序注释
29+
30+
![100](472.100.png)
Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,36 @@
11
package Problem0472
22

33
func findAllConcatenatedWordsInADict(words []string) []string {
4-
dict := make(map[int]map[string]bool)
4+
hasLen := make(map[int]bool, len(words))
5+
hasWord := make(map[string]bool, len(words))
56
for _, word := range words {
6-
if _, ok := dict[len(word)]; !ok {
7-
dict[len(word)] = make(map[string]bool)
8-
}
9-
dict[len(word)][word] = true
7+
hasLen[len(word)] = true
8+
hasWord[word] = true
109
}
1110

1211
res := make([]string, 0, len(words))
1312
for _, word := range words {
14-
if isConcatenated(word, dict, true) {
13+
if isConcatenated(word, hasLen, hasWord, true) {
1514
res = append(res, word)
1615
}
1716
}
1817

1918
return res
2019
}
2120

22-
func isConcatenated(word string, dict map[int]map[string]bool, isWordComplete bool) bool {
21+
func isConcatenated(word string, hasLen map[int]bool, hasWord map[string]bool, isWordComplete bool) bool {
2322
for wLen := 1; wLen < len(word); wLen++ {
24-
wordMap, ok := dict[wLen]
25-
if ok &&
26-
wordMap[word[:wLen]] &&
27-
isConcatenated(word[wLen:], dict, false) {
23+
if hasLen[wLen] &&
24+
// word[:wLen] 非常耗时,确保 wrods 存在长度为 wLen 的单词
25+
// 才检查 word[:wLen] 是否存在
26+
hasWord[word[:wLen]] &&
27+
isConcatenated(word[wLen:], hasLen, hasWord, false) {
2828
return true
2929
}
3030
}
3131

3232
// 单词是完整的时候,会匹配到自己, 需要剔除这种情况
3333
return !isWordComplete &&
34-
dict[len(word)][word]
34+
hasLen[len(word)] &&
35+
hasWord[word]
3536
}

0 commit comments

Comments
 (0)