Merge pull request #1128 from Guicai996/patch-1

修订 0139.单词拆分.md
This commit is contained in:
程序员Carl
2022-03-19 10:04:36 +08:00
committed by GitHub

View File

@ -89,27 +89,26 @@ class Solution {
private: private:
bool backtracking (const string& s, bool backtracking (const string& s,
const unordered_set<string>& wordSet, const unordered_set<string>& wordSet,
vector<int>& memory, vector<bool>& memory,
int startIndex) { int startIndex) {
if (startIndex >= s.size()) { if (startIndex >= s.size()) {
return true; return true;
} }
// 如果memory[startIndex]不是初始值了直接使用memory[startIndex]的结果 // 如果memory[startIndex]不是初始值了直接使用memory[startIndex]的结果
if (memory[startIndex] != -1) return memory[startIndex]; if (!memory[startIndex]) return memory[startIndex];
for (int i = startIndex; i < s.size(); i++) { for (int i = startIndex; i < s.size(); i++) {
string word = s.substr(startIndex, i - startIndex + 1); string word = s.substr(startIndex, i - startIndex + 1);
if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) { if (wordSet.find(word) != wordSet.end() && backtracking(s, wordSet, memory, i + 1)) {
memory[startIndex] = 1; // 记录以startIndex开始的子串是可以被拆分的
return true; return true;
} }
} }
memory[startIndex] = 0; // 记录以startIndex开始的子串是不可以被拆分的 memory[startIndex] = false; // 记录以startIndex开始的子串是不可以被拆分的
return false; return false;
} }
public: public:
bool wordBreak(string s, vector<string>& wordDict) { bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordSet(wordDict.begin(), wordDict.end()); unordered_set<string> wordSet(wordDict.begin(), wordDict.end());
vector<int> memory(s.size(), -1); // -1 表示初始化状态 vector<bool> memory(s.size(), 1); // -1 表示初始化状态
return backtracking(s, wordSet, memory, 0); return backtracking(s, wordSet, memory, 0);
} }
}; };