LeetCode 139: Word Break
Problem Description
Explanation
To solve this problem, we can use dynamic programming. We will create a boolean array dp
of size s.length() + 1
, where dp[i]
will be true if the substring s[0:i]
can be segmented into words from the dictionary. We iterate over the string s
and at each position, we check if any prefix of the current substring is in the dictionary and if the remaining suffix is also part of the segmented words.
Algorithm:
- Initialize a boolean array
dp
of sizes.length() + 1
wheredp[i]
indicates if the substrings[0:i]
can be segmented into words from the dictionary. - Set
dp[0] = true
since an empty string can be segmented. - Iterate over the string
s
and at each positioni
, iterate from0
toi
to check if any prefix of the current substring is in the dictionary and if the remaining suffix is also part of the segmented words. - Update
dp[i]
if the current substring can be segmented. - Return
dp[s.length()]
.
Time Complexity:
The time complexity of this solution is O(n^2) where n is the length of the input string s
.
Space Complexity:
The space complexity of this solution is O(n) where n is the length of the input string s
.
Solutions
class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> dict = new HashSet<>(wordDict);
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 1; i <= s.length(); i++) {
for (int j = 0; j < i; j++) {
if (dp[j] && dict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
Related LeetCode Problems
Loading editor...