forked from hrsvrdhn/DP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordBreak.java
More file actions
37 lines (35 loc) · 937 Bytes
/
wordBreak.java
File metadata and controls
37 lines (35 loc) · 937 Bytes
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
36
37
import java.util.*;
import java.io.*;
class wordBreak {
public void solveWordBreak(String word, Set<String> dictionary) {
boolean[][] dp = new boolean[word.length()][word.length()];
for(int i=0; i<dp.length; i++) {
if(dictionary.contains(word.substring(i, i+1)))
dp[i][i] = true;
}
for(int l=2; l<=dp.length; l++) {
for(int i=0; i<dp.length-l+1; i++) {
int j = i + l - 1;
if(dictionary.contains(word.substring(i, j+1))) {
dp[i][j] = true;
continue;
}
for(int k=i+1; k<=j; k++) {
if(dp[i][k-1] && dp[k][j]) {
dp[i][j] = true;
break;
}
}
}
}
System.out.println(dp[0][dp[0].length-1] ? "Possible" : "Not possible");
}
public static void main(String args[]) {
wordBreak obj = new wordBreak();
Set<String> s = new HashSet<>();
s.add("interview");
s.add("my");
s.add("trainer");
obj.solveWordBreak("myinterviewtrainer", s);
}
}