我正在尝试编写一个方法,该方法接受一个字符串的输入,并通过检查字符串的某些部分是否与字典单词匹配,返回一个可能的字符串列表,其中包含逻辑空格。例如:
例子:
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 "
}
我的代码目前是
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]);
我知道 for 循环是问题,但我似乎找不到错误。我正在打印
be
cause
to
day
us
use
a
today
us
use
a
because
to
day
us
use
a
today
us
use
a
任何帮助将不胜感激 :)