时间轴

2025-12-13

init


题目:

dp[i] 表示 s[0..i-1] 这个前缀是否可以被成功拆分成字典里的单词。dp[0] = true,即空字符串可被拆分。
dp[i]等于 true 的条件是,dp[j](0 <= j < i)为 true,且 s.substr(j, i-j)是 wordDict 中的一个单词。

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
#include <string>
#include <vector>
#include <unordered_set>
using std::vector;
using std::string;
using std::unordered_set;

class Solution {
public:
bool wordBreak(string s, vector<string> &wordDict)
{
int i, j, n = s.size();
unordered_set<string> dict(wordDict.begin(), wordDict.end());
// dp[i] 表示 s[0..i-1] 这个前缀是否可以被成功拆分
vector<bool> dp(n + 1, false);
dp[0] = true; // 空字符串可以被拆分
for (i = 1; i <= n; i++) {
for (j = 0; j < i; j++) { // s[0..i-1]
//
if (dp[j] && dict.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp[n];
}
};

leetcode hot 100 rewrite:用了前缀树+BFS写法

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
#include <string>
#include <vector>
#include <queue>

using std::vector;
using std::string;
using std::queue;

struct TrieNode {
vector<TrieNode *> children;
char data;
bool is_end;

TrieNode()
{
this->children = vector<TrieNode *>(26, nullptr);
this->is_end = false;
}
};

class Solution {
public:
bool wordBreak(string s, vector<string> &wordDict)
{
// 1 <= s.length <= 300
// 1 <= wordDict.length <= 1000
// 1 <= wordDict[i].length <= 20
// s 和 wordDict[i] 仅由小写英文字母组成
// wordDict 中的所有字符串 互不相同

TrieNode *root = new TrieNode, *p;
int i, n = s.size();

for (string word : wordDict) {
p = root;

for (char ch : word) {
if (p->children[ch - 'a'] == nullptr)
p->children[ch - 'a'] = new TrieNode;

p = p->children[ch - 'a'];
p->data = ch;
}
p->is_end = true;
}

queue<int> que;
vector<bool> visited(n, false);
que.push(0);
visited[0] = true;

while (!que.empty()) {
int start = que.front();
que.pop();
if (start == n)
return true;

p = root;
for (i = start; i < n; i++) {
if (p->children[s[i] - 'a'] == nullptr)
break;

p = p->children[s[i] - 'a'];

if (p->is_end && !visited[i + 1]) {
que.push(i + 1);
visited[i + 1] = true;
}
}
}

return false;
}
};