我如何使用预设的字符串列表来分割一个字符串,并在它们之间添加空格?
例如:
字符串列表:
例如:
字符串列表:
words = {"hello", "how", "are", "you"}
要分割的字符串: text = "hellohowareyou"
public static String separateText(String text, List<String> words) {
String new_text;
for (String word : words) {
if (text.startsWith(word)) {
String suffix = text.substring(word.length()); //'suffix' is the 'text' without it's first word
new_text += " " + word; //add the first word of the 'string'
separateString(suffix, words);
}
}
return new_text;
}
而 new_text
应该返回 你好吗 你好吗
请注意列表words
的顺序可能不同,也可能有更多单词,就像一个字典。
如果需要,我要如何进行递归?
[an, of, or, range, orange]
,都无法正确分隔),排序并不能帮助太多。但是除此之外,你的解决方案具有 O(n * m) 的时间复杂度(其中 m 是文本长度,n 是字典大小),我同意它至少是一个很好的起点。 - dshelya