Skip to content

Commit 538af44

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 139_Word_Break.java
1 parent aca076e commit 538af44

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

Dynamic Programming/139_Word_Break.java

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,20 @@ public boolean wordBreak(String s, List<String> wordDict) {
33
if (s == null || s.length() == 0) {
44
return false;
55
}
6-
return helper(s, new HashSet<>(wordDict), new HashMap<>());
7-
}
8-
9-
private boolean helper(String s, Set<String> wordDict, Map<String, Boolean> memo) {
10-
if (s.length() == 0) {
11-
return true;
12-
}
136

14-
if (memo.containsKey(s)) {
15-
return memo.get(s);
16-
}
7+
Set<String> dict = new HashSet<>(wordDict);
178

18-
for (int i = 0; i <= s.length(); i++) {
19-
String prefix = s.substring(0, i);
20-
String remainder = s.substring(i, s.length());
9+
boolean[] dp = new boolean[s.length() + 1];
10+
dp[0] = true;
2111

22-
if (wordDict.contains(prefix) && helper(remainder, wordDict, memo)) {
23-
memo.put(s, true);
24-
return memo.get(s);
12+
for (int i = 1; i <= s.length(); i++) {
13+
for (int j = 0; j < i; j++) {
14+
if (dp[j] && dict.contains(s.substring(j, i))) {
15+
dp[i] = true;
16+
}
2517
}
2618
}
2719

28-
memo.put(s, false);
29-
return memo.get(s);
20+
return dp[s.length()];
3021
}
3122
}

0 commit comments

Comments
 (0)