139. Word Break LeetCode Solution
In this guide, you will get 139. Word Break LeetCode Solution with the best time and space complexity. The solution to Word Break problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Word Break solution in C++
- Word Break solution in Java
- Word Break solution in Python
- Additional Resources
Problem Statement of Word Break
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Example 1:
Input: s = “leetcode”, wordDict = [“leet”,”code”]
Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.
Example 2:
Input: s = “applepenapple”, wordDict = [“apple”,”pen”]
Output: true
Explanation: Return true because “applepenapple” can be segmented as “apple pen apple”.
Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = “catsandog”, wordDict = [“cats”,”dog”,”sand”,”and”,”cat”]
Output: false
Constraints:
1 <= s.length <= 300
1 <= wordDict.length <= 1000
1 <= wordDict[i].length <= 20
s and wordDict[i] consist of only lowercase English letters.
All the strings of wordDict are unique.
Complexity Analysis
- Time Complexity: O(n^3)
- Space Complexity: O(n^2 + \Sigma |\texttt{wordDict[i]}|)
139. Word Break LeetCode Solution in C++
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
return wordBreak(s, {wordDict.begin(), wordDict.end()}, {});
}
private:
bool wordBreak(const string& s, const unordered_set<string>&& wordSet,
unordered_map<string, bool>&& mem) {
if (wordSet.contains(s))
return true;
if (const auto it = mem.find(s); it != mem.cend())
return it->second;
// 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.contains(prefix) &&
wordBreak(suffix, std::move(wordSet), std::move(mem)))
return mem[s] = true;
}
return mem[s] = false;
}
};
/* code provided by PROGIEZ */
139. Word Break LeetCode Solution in Java
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> mem) {
if (mem.containsKey(s))
return mem.get(s);
if (wordSet.contains(s)) {
mem.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, mem)) {
mem.put(s, true);
return true;
}
}
mem.put(s, false);
return false;
}
}
// code provided by PROGIEZ
139. Word Break LeetCode Solution in Python
class Solution:
def wordBreak(self, s: str, wordDict: list[str]) -> bool:
wordSet = set(wordDict)
@functools.lru_cache(None)
def wordBreak(s: str) -> bool:
"""Returns True if s can be segmented."""
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)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.