給出以下字符:「R」,「G」,「B」和「X」。必須逐個將它們添加到長度從0到5變化的現有String
中。該長度包括特殊字符/
。即,現有的字符串可能像:如何向排序順序中的現有字符串添加新字符?
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
塊。我怎樣才能做到這一點?謝謝。
嘗試使用列表 listString = new ArrayList (); –
andreich
@andreich,那麼我將如何對那個'listString'進行排序呢? :) – ozbek
Collections.sort(listString); – andreich