时间轴
时间轴
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 中的一个单词。
12345678910111213141516171819202122232425262728 | 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写法
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 | 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; }}; |
