LeetCode Solutions
139. Word Break
Time: $O(n^3)$ Space: $O(n^2 + \Sigma |\texttt{wordDict[i]}|)$
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
return wordBreak(s, {begin(wordDict), end(wordDict)}, {});
}
private:
bool wordBreak(const string& s, const unordered_set<string>&& wordSet,
unordered_map<string, bool>&& memo) {
if (wordSet.count(s))
return true;
if (memo.count(s))
return memo[s];
// 1 <= prefix.length() < s.length()
for (int i = 1; i < s.length(); ++i) {
const string& prefix = s.substr(0, i);
const string& suffix = s.substr(i);
if (wordSet.count(prefix) && wordBreak(suffix, move(wordSet), move(memo)))
return memo[s] = true;
}
return memo[s] = false;
}
};
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
return wordBreak(s, new HashSet<>(wordDict), new HashMap<>());
}
private boolean wordBreak(final String s, Set<String> wordSet, Map<String, Boolean> memo) {
if (memo.containsKey(s))
return memo.get(s);
if (wordSet.contains(s)) {
memo.put(s, true);
return true;
}
// 1 <= prefix.length() < s.length()
for (int i = 1; i < s.length(); ++i) {
final String prefix = s.substring(0, i);
final String suffix = s.substring(i);
if (wordSet.contains(prefix) && wordBreak(suffix, wordSet, memo)) {
memo.put(s, true);
return true;
}
}
memo.put(s, false);
return false;
}
}
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
wordSet = set(wordDict)
@functools.lru_cache(None)
def wordBreak(s: str) -> bool:
if s in wordSet:
return True
return any(s[:i] in wordSet and wordBreak(s[i:]) for i in range(len(s)))
return wordBreak(s)