- Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode140-word-break-ii_trie_and_dfs.cpp
93 lines (86 loc) · 2.43 KB
/
leetcode140-word-break-ii_trie_and_dfs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include<vector>
#include<string>
#include<algorithm>
#include<iostream>
usingnamespacestd;
classSolution {
structTrieNode
{
TrieNode* next[26];
bool isEnd;
TrieNode()
{
isEnd = false;
for (int i = 0; i < 26; i++)
next[i] = nullptr;
}
// ~TrieNode()
// {
// for (auto node : next) delete node;
// }
};
TrieNode* root;
int failMemo[301]; // 记录dfs中失败时对应的s中的index
vector<string> res;
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
root = newTrieNode();
for (auto word : wordDict)
{
TrieNode* node = root;
for (auto ch : word)
{
if (node->next[ch - 'a'] == nullptr)
node->next[ch - 'a'] = newTrieNode();
node = node->next[ch - 'a'];
}
node->isEnd = true;
}
vector<string> curWords;
dfs(s, 0, curWords);
return res;
}
booldfs(string& s, int startPos, vector<string>& curWords)
{
if (failMemo[startPos] == 1) returnfalse;
if (startPos == s.size())
{
string sen; // 句子
for (auto& word : curWords)
sen += word + "";
sen.pop_back(); // 删掉最后一个空格
res.push_back(sen);
returntrue;
}
TrieNode* node = root;
bool flag = false;
for (int i = startPos; i < s.size(); i++)
{
if (node->next[s[i] - 'a'] != nullptr)
{
node = node->next[s[i] - 'a'];
if (node->isEnd == true)
{
curWords.push_back(s.substr(startPos, i - startPos + 1));
if (dfs(s, i + 1, curWords))
flag = true;
curWords.pop_back();
}
}
elsebreak;
}
if (flag == false) failMemo[startPos] = 1;
return flag;
}
};
// Test
intmain()
{
Solution sol;
string s = "catsanddog";
vector<string> wordDict = {"cat", "cats", "and", "sand", "dog"};
auto res = sol.wordBreak(s, wordDict); /* 我安装的vs code或minGW或gdb有bug, 结果是{}. 用Dev C++运行正常 */
for (auto& path : res)
cout << path << endl;
return0;
}