Published
- 2 min read
Word break problem BFS
Word break BFS problem
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. By space segmented means if we can reach the end of the string, because if the string can be broken into any dictionary words only then we can reach the end
Why this is a dp problem - because we are asked to break the string into words, at each step we are making a sub problem
- While using BFS you can add the start index into the start of the queue After that you need to iterate till you find the first end which forms the right substring Start from that end as teh next start, if you do this way you will see moving to the end of the string.
- Hand drawn diagram to explaining the recursion
private boolean wordBreak(String s, String dict[]) {
HashSet<String> dictSet = new HashSet<>();
boolean[] seen = new boolean[s.length() + 1];
for(int i =0; i < dict.length; i++) {
dictSet.add(dict[i]);
}
Queue<Integer> queue = new LinkedList();
queue.add(0);
while (!queue.isEmpty()) {
int startIndex = queue.poll();
if(startIndex == s.length()) {
return true;
}
/**what is changing, endindex?? yes because its getting incremented each time */
for ( int endIndex = startIndex+1; endIndex <= s.length(); endIndex++) {
if(seen[endIndex]) {
continue; //already given true result so no need to check it again or run for loop for it
}
if(dictSet.contains(s.substring(startIndex, endIndex))) {
seen[endIndex] = true;
queue.add(endIndex);
break; //added to move to next index immediately
}
}
}
return seen[s.length()];
}