以下是迭代風格的解決方案(主要思想是將問題分解爲:在輸入的特定範圍內找到具有正確的1,2,3..n分段單詞的分割。請問是否存在任何次要索引錯誤,這些天我的頭很模糊,但這對你來說是一個迭代的解決方案。):
static List<String> connectIter(List<String> tokens) {
// use instead of array, the key is of the from 'int int'
Map<String, List<String>> data = new HashMap<String, List<String>>();
int n = tokens.size();
for(int i = 0; i < n; i++) {
String str = concat(tokens, i, n);
if (dictContains(str)) {
data.put(1 + " " + i, Collections.singletonList(str));
}
}
for (int i = 2; i <= n; i++) {
for (int start = 0; i < n; start++) {
List<String> solutions = new ArrayList<String>();
for (int end = start + 1; end <= n - i + 1; end++) {
String firstPart = concat(tokens, start, end);
if (dictContains(firstPart)) {
List<String> partialSolutions = data.get((i - 1) + " " + end);
if (partialSolutions != null) {
List<String> newSolutions = new ArrayList<>();
for (String onePartialSolution : partialSolutions) {
newSolutions.add(firstPart + " "
+ onePartialSolution);
}
solutions.addAll(newSolutions);
}
}
}
if (solutions.size() != 0) {
data.put(i + " " + start, solutions);
}
}
}
List<String> ret = new ArrayList<String>();
for(int i = 1; i <= n; i++) { // can be optimized to run with less iterations
List<String> solutions = data.get(i + " " + 0);
if (solutions != null) {
ret.addAll(solutions);
}
}
return ret;
}
static private String concat(List<String> tokens, int low, int hi) {
StringBuilder sb = new StringBuilder();
for(int i = low; i < hi; i++) {
sb.append(tokens.get(i));
}
return sb.toString();
}
爲什麼這不得不比在每個空格字符處分割字符串更困難? – 2009-11-23 07:49:17
查看我的答案舉個例子,d。 – Amber 2009-11-23 07:53:09
是的空間被刪除的字符串。 Dav,如果你有一個有效的單詞列表,你會怎麼做,所以你還必須檢查一個單詞是否有效?我很難理解你的實現。 – Bill 2009-11-23 08:34:37