-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0139.java
More file actions
35 lines (32 loc) · 1.09 KB
/
Copy pathLeetCode0139.java
File metadata and controls
35 lines (32 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* Word Break
* Input: s = "applepenapple", wordDict = ["apple", "pen"]
* Output: true
* Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
* Output: false
* */
import java.util.ArrayList;
import java.util.List;
public class LeetCode0139 {
public static void main(String args[]) {
String s = "applepenapple";
List<String> wordDict = new ArrayList<String>();
wordDict.add("apple");
wordDict.add("pen");
System.out.println(wordBreak(s, wordDict));
}
public static boolean wordBreak(String s, List<String> wordDict) {
boolean[] dp = new boolean[s.length() + 1];
dp[0] = true;
for (int i = 0; i < s.length() + 1; i++) {
if (dp[i] != true)
continue;
for(String word : wordDict){
if(i + word.length() > s.length())
continue;
if(s.substring(i, i+word.length()).equals(word))
dp[i + word.length()] = true;
}
}
return dp[s.length()];
}
}