Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active May 27, 2018 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/3077360b819ec513ff5ab61e9cb34638 to your computer and use it in GitHub Desktop.
Save thmain/3077360b819ec513ff5ab61e9cb34638 to your computer and use it in GitHub Desktop.
import java.util.HashSet;
public class WordBreakRecursion {
public void wordBreak(String s, HashSet<String> hs) {
if (find(s, hs, "")) {
} else {
System.out.println("Cant Break");
}
}
public boolean find(String s, HashSet<String> dict, String answer) {
// System.out.println(s + " " + answer);
if (s.length() == 0) {
System.out.println(answer);
return true;
} else {
int index = 0;
String word = "";
while (index < s.length()) {
word += s.charAt(index);// add one char at a time
// check if word exists in dictionary
if (dict.contains(word)) {
//add word to the answer and make a recursive call
if (find(s.substring(index + 1), dict, answer + word + " ")) {
return true;
} else {
//System.out.println(word + " backtrack");
index++;
}
} else {
index++;
}
}
return false;
}
}
public static void main(String[] args) {
HashSet<String> hs = new HashSet<String>();
hs.add("this");
hs.add("is");
hs.add("sumit");
hs.add("jain");
hs.add("the");
hs.add("problem");
String s = "thisissumitjain";
WordBreakRecursion ws = new WordBreakRecursion();
ws.wordBreak(s, hs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment