I have written a code using java on word break problem. This idea is to return the list of words from the dictionary which when combined give the entered string. I have used TRIE data structure in my approach. It is working fine for positive cases, however, it is not working as expected for negative cases.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class WordBreakProblem {
public class Node{
String prefix;
Map<Character, Node> children;
boolean isWord;
public Node(String prefix){
this.prefix = prefix;
children = new HashMap<Character, Node>();
isWord = false;
}
}
Node trie;
public WordBreakProblem(String[] words){
trie = new Node("");
for(String s : words){
insertIntoTrie(s);
}
}
private void insertIntoTrie(String s) {
Node curr = trie;
for(int i=0; i<s.length(); i++){
if(!curr.children.containsKey(s.charAt(i)))
curr.children.put(s.charAt(i), new Node(s.substring(0, i+1)));
curr = curr.children.get(s.charAt(i));
if(i == s.length()-1)
curr.isWord = true;
}
}
public ArrayList<String> searchForPair(String str, ArrayList<String> list){
Node curr = trie;
int i;
for(i = 0; i<str.length(); i++){
if(curr.children.containsKey(str.charAt(i))){
curr = curr.children.get(str.charAt(i));
}
else
break;
}
if(curr.isWord){
list.add(curr.prefix);
searchForPair(str.substring(i), list);
}
else
return null;
return list;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
WordBreakProblem w = new WordBreakProblem(new String[]{"news", "abcd", "tree", "geeks", "paper"});
List<String> al = w.searchForPair("newsgeeksabc", list);
for(String s : al){
System.out.println(s);
}
}
}
Expected: null
Output:
news
geeks
Since "abc" is not present in the dictionary, it should return null.
The problem seems to be somewhere here:
if(curr.isWord){
list.add(curr.prefix);
searchForPair(str.substring(i), list);
}
else
return null;