- Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode139-word-break_trie_and_dfs.cpp
68 lines (65 loc) · 1.65 KB
/
leetcode139-word-break_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
#include<vector>
#include<algorithm>
#include<iostream>
#include<bits/stdc++.h>
usingnamespacestd;
structTrieNode {
TrieNode* next[26];
bool isEnd;
TrieNode()
{
for (int i = 0; i < 26; i++)
next[i] = nullptr;
isEnd = false;
}
};
classSolution {
TrieNode* root;
int failMemo[301]; // 记录dfs中失败时对应的s中的index
public:
boolwordBreak(string s, vector<string>& wordDict) {
root = newTrieNode();
// 建树
for (auto& word : wordDict)
{
TrieNode* p = root;
for (auto& ch : word)
{
if (p->next[ch - 'a'] == nullptr)
p->next[ch - 'a'] = newTrieNode();
p = p->next[ch - 'a'];
}
p->isEnd = true;
}
returndfs(s, 0);
}
booldfs(string& s, int startPos)
{
if (failMemo[startPos] == 1) returnfalse;
if (startPos == s.size()) returntrue;
TrieNode* p = root;
for (int i = startPos; i < s.size(); i++)
{
if (p->next[s[i] - 'a'] != nullptr)
{
p = p->next[s[i] - 'a'];
if (p->isEnd == true && dfs(s, i+1))
returntrue;
}
elsebreak;
}
failMemo[startPos] = 1;
returnfalse;
}
};
// Test
intmain()
{
Solution sol;
string s = "applepenapple";
vector<string> wordDict = {"apple", "pen"};
// 预期输出: true
auto res = sol.wordBreak(s, wordDict);
cout << (res == true ? "true" : "false");
return0;
}