Skip to content

Instantly share code, notes, and snippets.

@thmain
Created May 27, 2018 06:19
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/d3486c2dcd0eca0fbee27edaf9c8dbef to your computer and use it in GitHub Desktop.
Save thmain/d3486c2dcd0eca0fbee27edaf9c8dbef to your computer and use it in GitHub Desktop.
import java.util.HashSet;
public class WordBreak {
public boolean findUsingDP(String s, HashSet<String> dict,
HashSet<String> memory, String answer) {
if (s.length() == 0) {
System.out.println(answer);
return true;
} else if (memory.contains(s)) {
return false;
} else {
int index = 0;
String word = "";
while (index < s.length()) {
word += s.charAt(index);// add one char at a time
// check if word already being solved
if (dict.contains(word)) {
if (findUsingDP(s.substring(index + 1), dict, memory,
answer + word + " ")) {
return true;
} else {
System.out.println("backtrack");
index++;
}
} else {
index++;
}
}
memory.add(s);// memoization for future;
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";
WordBreak ws = new WordBreak();
// create another HashSet so store the sub problems result
HashSet<String> memoization = new HashSet<String>();
ws.findUsingDP(s, hs, memoization, "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment