如何生成由单词字符串的特定单词组合构成的子字符串数组
连续单词组合生成方法
从你给出的示例来看,需求是生成输入字符串中所有连续相邻的单词组合,不改变原有单词顺序,覆盖长度从1到总单词数的所有情况。
核心实现步骤
- 第一步:将输入字符串按空格分割为独立的单词数组
- 第二步:双层遍历生成所有合法的连续单词区间:
- 第一层遍历控制组合的单词长度(从1到总单词数)
- 第二层遍历控制组合的起始位置,保证组合不越界
- 第三步:将每个区间的单词拼接为字符串,存入结果数组即可
如果需要匹配示例给出的输出顺序,可对最终结果数组按长度升序、自定义规则排序即可。
参考示例验证
输入:
United States America
输出:["United", "States", "America", "States America", "United States", "United States America"]
代码实现
Python 版本
def generate_word_combinations(input_str): words = input_str.split() word_count = len(words) result = [] # 遍历所有组合长度 for length in range(1, word_count + 1): # 遍历所有合法起始位置 for start_idx in range(word_count - length + 1): combination = ' '.join(words[start_idx: start_idx + length]) result.append(combination) return result # 测试运行 test_input = "United States America" print(generate_word_combinations(test_input))
JavaScript 版本
function generateWordCombinations(inputStr) { const words = inputStr.split(' '); const wordCount = words.length; const result = []; // 遍历所有组合长度 for (let length = 1; length <= wordCount; length++) { // 遍历所有合法起始位置 for (let startIdx = 0; startIdx <= wordCount - length; startIdx++) { const combination = words.slice(startIdx, startIdx + length).join(' '); result.push(combination); } } return result; } // 测试运行 const testInput = "United States America"; console.log(generateWordCombinations(testInput));
复杂度说明
如果单词总数为n,该方法的时间复杂度为O(n²),空间复杂度为O(n²),常规场景下性能足够使用。
内容的提问来源于stack exchange,提问作者Rafiq
相关产品推荐
相关产品推荐

