Skip to content

Commit b115010

Browse files
committed
feat: solve word break
1 parent b1f1306 commit b115010

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

word-break/GangBean.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public boolean wordBreak(String s, List<String> wordDict) {
3+
/**
4+
1. understanding
5+
- check if s's segments are all in wordDict.
6+
- wordDict can be used multiple times
7+
2. strategy
8+
a) dynamic programming
9+
- dp[k]: substring(0,k+1) can be constructed by wordDict.
10+
- dp[0]: false
11+
- dp[1]: substring(0, 2) in wordDict
12+
- dp[k+1] = substring(0, k+2) in wordDict || Any(dp[k] && substring(k+1, k+2) in wordDict)
13+
- return dp[s.length()]
14+
3. complexity
15+
- time: O(N^2 * S), where N is the length of s, S is search time each segment in wordDict. You can calculate S in O(1) time, when change wordDict to Set. so O(N) is final time complexity.
16+
- space: O(N + W), W is the size of wordDict
17+
*/
18+
Set<String> bow = new HashSet<>(wordDict);
19+
boolean[] dp = new boolean[s.length() + 1];
20+
21+
for (int i = 1; i < dp.length; i++) { // O(N)
22+
String segment = s.substring(0, i);
23+
dp[i] = bow.contains(segment);
24+
for (int j = 0; j < i; j++) { // O(N)
25+
if (dp[i]) break;
26+
segment = s.substring(j, i);
27+
dp[i] = dp[i] || (dp[j] && bow.contains(segment)); // O(1)
28+
}
29+
}
30+
31+
return dp[s.length()];
32+
}
33+
}
34+

0 commit comments

Comments
 (0)