Skip to content

Commit 6c91538

Browse files
139. Word Break (java)
1 parent 2101946 commit 6c91538

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public boolean wordBreak(String s, List<String> wordDict) {
3+
int wordMaxLen = Integer.MIN_VALUE;
4+
for (String word : wordDict){
5+
wordMaxLen = Math.max(wordMaxLen, word.length());
6+
}
7+
Set<String> wordSet = new HashSet<>(wordDict);
8+
int len = s.length();
9+
boolean[] dp = new boolean[len + 1];
10+
dp[0] = true;
11+
for(int i = 1; i <= len; i++){
12+
for(int l = 1; l <= wordMaxLen && i - l >= 0; l++){
13+
if(dp[i-l] && wordSet.contains(s.substring(i-l, i))){
14+
dp[i] = true;
15+
break;
16+
}
17+
}
18+
}
19+
return dp[len];
20+
}
21+
}

0 commit comments

Comments
 (0)