【发布时间】:2013-08-21 08:53:11
【问题描述】:
给定以下字符:“R”、“G”、“B”和“X”。它们必须一次添加到现有的String,其长度从 0 到 5 不等。此长度包括特殊字符 /。即,现有字符串可能如下所示:
null- “”(空字符串)
- “G”
- “B/X”
- “G/B”
- “R/G/B”
- 等(上述的其他变体)
最终字符串的顺序应该始终为 "G/R/B/X":
-
G必须是第一项。 -
X必须是最后一项。 -
R必须在G之后和B之前。 -
B必须在R之后。
这些字符中的任何一个可能存在也可能不存在。
如果现有字符串只有一个字符,看起来很简单:
private String sortThemAll(String existingString, String newString) {
if (TextUtils.isEmpty(existingString)) {
return newString;
}
if (existingString.length() == 1) {
List<String> list = Arrays.asList(existingString, newString);
if (list.contains("G") && list.contains("R")) {
Collections.sort(list);
} else {
Collections.sort(list, Collections.reverseOrder());
}
return list.get(0).concat("/").concat(list.get(1));
}
if (existingString.length() == 3) { // e.g., "B/X"
// Assuming that existingString is already sorted
if ("G".equals(newString)) {
// G should always be the first item on the list
return newString.concat("/").concat(existingString);
}
if ("X".equals(newString)) {
// X should always be the last item on the list
return existingString.concat("/").concat(newString);
}
/*** I don't know how I should proceed from this point ***/
}
return existingString.concat("/").concat(newString);
}
我在这个问题中看不到任何模式,我能想到的只是几个嵌套的if/else 块。我怎样才能做到这一点?谢谢。
【问题讨论】:
-
尝试使用 List
listString = new ArrayList (); -
@andreich,那我将如何对
listString进行排序? :) -
Collections.sort(listString);
-
那将按字母顺序对列表进行排序?您可能已经注意到最终字符串中的字符不是按字母顺序排序的。