Skip to main content

Posts

Showing posts from February, 2020

Word Break Problem - auto separate the words from a given string checking dictionary.

Word Break Problem - auto separate the words from a given string checking dictionary. Function to segment given String into a space-separated sequence of one or more dictionary words import java.util.Arrays; import java.util.List; public class TestMain { // Function to segment given String into a space-separated // sequence of one or more dictionary words public static void wordBreak(List<String> dict, String str, String out) { // if we have reached the end of the String, // print the output String if (str.length() == 0) { System.out.println(out); return; } for (int i = 1; i <= str.length(); i++) { // consider all prefixes of current String String prefix = str.substring(0, i); // if the prefix is present in the dictionary, add prefix to the // output String and recur for remaining String if (dict.contains(prefix)) { wordBreak(dict, str.substring(i), out + " " + prefix