Last active
May 27, 2018 06:23
-
-
Save thmain/3077360b819ec513ff5ab61e9cb34638 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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