|
| 1 | +// A recursive program to print all possible |
| 2 | +// partitions of a given string into dictionary |
| 3 | +// words |
| 4 | +import java.io.*; |
| 5 | +import java.util.*; |
| 6 | + |
| 7 | +class GFG { |
| 8 | + |
| 9 | +// Prints all possible word breaks of given string |
| 10 | +static void wordBreak(int n, List<String> dict, String s) |
| 11 | +{ |
| 12 | + String ans=""; |
| 13 | + wordBreakUtil(n, s, dict, ans); |
| 14 | +} |
| 15 | + |
| 16 | +static void wordBreakUtil(int n, String s, List<String> dict, String ans) |
| 17 | +{ |
| 18 | + for(int i = 1; i <= n; i++) |
| 19 | + { |
| 20 | + |
| 21 | + // Extract substring from 0 to i in prefix |
| 22 | + String prefix=s.substring(0, i); |
| 23 | + |
| 24 | + // If dictionary contains this prefix, then |
| 25 | + // we check for remaining string. Otherwise |
| 26 | + // we ignore this prefix (there is no else for |
| 27 | + // this if) and try next |
| 28 | + if(dict.contains(prefix)) |
| 29 | + { |
| 30 | + // If no more elements are there, print it |
| 31 | + if(i == n) |
| 32 | + { |
| 33 | + |
| 34 | + // Add this element to previous prefix |
| 35 | + ans += prefix; |
| 36 | + System.out.println(ans); |
| 37 | + return; |
| 38 | + } |
| 39 | + wordBreakUtil(n - i, s.substring(i,n), dict, ans+prefix+" "); |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +// main function |
| 45 | +public static void main(String args[]) |
| 46 | +{ |
| 47 | + String str1 = "iloveicecreamandmango"; // for first test case |
| 48 | + String str2 ="ilovesamsungmobile"; // for second test case |
| 49 | + int n1 = str1.length(); // length of first string |
| 50 | + int n2 = str2.length(); // length of second string |
| 51 | + |
| 52 | + // List of strings in dictionary |
| 53 | + List <String> dict= Arrays.asList("mobile","samsung","sam","sung", |
| 54 | + "man","mango", "icecream","and", |
| 55 | + "go","i","love","ice","cream"); |
| 56 | + System.out.println("First Test:"); |
| 57 | + |
| 58 | + // call to the method |
| 59 | + wordBreak(n1,dict,str1); |
| 60 | + System.out.println("\nSecond Test:"); |
| 61 | + |
| 62 | + // call to the method |
| 63 | + wordBreak(n2,dict,str2); |
| 64 | +} |
| 65 | +} |
| 66 | + |
| 67 | +// This code is contributed by mohitjha727. |
0 commit comments