I am trying to write a method that takes an input of a string, and returns a list of possible strings in which logical spaces have been included by checking to see if parts of the string match dictionary words. For example:
Example:
input: "becausetodayuseat"
Output: {
"be cause to day us eat ",
"be cause to day use at ",
"be cause today us eat ",
"be cause today use at ",
"because to day us eat ",
"because to day use at ",
"because today us eat ",
"because today use at "
}
My code is currently
public static String[] space(String[] dict, String s) {
LinkedList<String> ret = new LinkedList<String>();
// base case
if (s.length() == 0) {
String[] r = { "" };
return r;
}
for (int i = 1; i < s.length(); i++) {
String prefix = s.substring(0, i);
if (inDictionary(dict, prefix)) {
prefix = prefix + " ";
ret.add(prefix);
String suffix = s.substring(i);
String[] end = space(dict,suffix);
//System.out.println(end.length);
for (int j = 0; j < end.length; ++j) {
ret.add(end[j]);
}
}
}
// This line converts LinkedList<String> to String []
return ret.toArray(new String[0]);
I know the for loop is the problem but I can't seem to find the bug. I am printing out
be
cause
to
day
us
use
a
today
us
use
a
because
to
day
us
use
a
today
us
use
a
Any help would be greatly appreciated :)