Created
June 12, 2020 13:52
-
-
Save LYP951018/ae20f0c9277aafc6a46f36c6a437ff07 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool wordBreak(string s, vector<string>& wordDict) { | |
if (s.empty()) | |
{ | |
return false; | |
} | |
if (wordDict.empty()) | |
{ | |
return false; | |
} | |
std::size_t minLen = 0; | |
for (const std::string& word: wordDict) | |
{ | |
minLen = std::min(word.size(), minLen); | |
if (s == word) | |
{ | |
return true; | |
} | |
std::size_t pos = s.find(word); | |
while (pos != std::string::npos) | |
{ | |
dp[pos][word.size()] = true; | |
pos = s.find(word, pos + 1); | |
} | |
} | |
if (s.size() < 2 * minLen) | |
{ | |
return false; | |
} | |
for (int i = 0; i < s.size(); ++i) | |
{ | |
for (int j = minLen * 2; j <= s.size() - i; ++j) | |
{ | |
for (int k = minLen; k < j; ++k) | |
{ | |
const bool breakable = dp[i][k] && dp[k][j - k]; | |
if (breakable) | |
{ | |
dp[i][j] = true; | |
break; | |
} | |
} | |
} | |
} | |
return dp[0][s.size()]; | |
} | |
private: | |
bool dp[1000][1000]{}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment