import java.util.List;
import java.util.Arrays;
public class WordBreakRecursive {
public static boolean isInDict(String word, List<String> dict) {
for (String d : dict) {
if (d.equals(word)) {
return true;
}
}
return false;
}
public static void wordBreak(String str, int strSize, String result, List<String> dict) {
for (int i = 1; i <= strSize; i++) {
String subStr = str.substring(0, i);
if (isInDict(subStr, dict)) {
if (i == strSize) {
result += subStr;
System.out.println(result);
return;
}
wordBreak(str.substring(i), strSize - i, result + subStr + " ", dict);
}
}
}
public static void main(String[] args) {
String str = "butterflyplaybasketballwithbags";
List<String> dict = Arrays.asList(
"butterfly", "basketball", "bagpiper", "and", "play",
"with", "butter", "fly", "basket", "ball", "bags"
);
wordBreak(str, str.length(), "", dict);
}
}
/*
run:
butter fly play basket ball with bags
butter fly play basketball with bags
butterfly play basket ball with bags
butterfly play basketball with bags
*/