-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordBreak.java
More file actions
47 lines (41 loc) · 1.18 KB
/
Copy pathWordBreak.java
File metadata and controls
47 lines (41 loc) · 1.18 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
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.Arrays;
import java.util.HashSet;
public class WordBreak {
private static final String[] SET_VALUES =
new String[] {"I", "have", "Jain", "Sumit", "am", "this", "dog"};
private static HashSet<String> dict = new HashSet<String>(Arrays.asList(SET_VALUES));
public static void wordBreak(String string, HashSet<String> hashSet) {
if (find(string, hashSet, "")) {
} else {
System.out.println("can't break");
}
}
private static boolean find(String string, HashSet<String> dict, String answer) {
if (string.length() == 0) {
System.out.println(answer);
return true;
}
int index = 0;
String word = "";
while (index < string.length()) {
word += string.charAt(index); // add one char at a time
// check if word is present in dict
if (dict.contains(word)) {
// add word to the answer and make a recursive call
if (find(string.substring(index + 1), dict, answer + word + " ")) {
return true;
} else {
// backtrack
index++;
}
} else {
index++;
}
}
return false;
}
public static void main(String[] args) {
wordBreak("IamSumit", dict); // I am Sumit
wordBreak("ImSumit", dict); // can't break
}
}