You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript生成字符串相邻单词去空格的所有组合

问题说明

给定输入字符串:

'test string of whole words'

需要生成字符串数组,覆盖所有移除连续相邻单词间空格、其余空格保留的单词组合结果,预期输出如下:

test string of whole words
teststring of whole words
test stringof whole words
test string ofwhole words
test string of wholewords
teststringof whole words
test stringofwhole words
test string ofwholewords
teststringofwhole words
test stringofwholewords
teststringofwholewords

现有初步代码仅支持每次移除单个空格,无法生成全部结果,代码如下:

function getSpaceIndices(str) {
  let spaceIndices = []
  for (let i = 0; i < str.length; i++) {
    if (str[i] === " ") {
      spaceIndices.push(i)
    }
  }
  return spaceIndices
}

let str = 'test string of whole words'
let strArray = str.split(" ");
let combinationArray = []

// let spaceRemoveCount = 1
let spaceIndices = getSpaceIndices(str)
let currentIndex = 0
while (currentIndex < spaceIndices.length) {
  let tempStr = str.slice(0, spaceIndices[currentIndex]) + str.slice(spaceIndices[currentIndex] + 1);
  combinationArray.push(tempStr);
  currentIndex++
}
console.log(combinationArray);
实现逻辑

观察预期结果规律:5个单词间共有4个空格位置,所有合法结果对应的移除空格都是连续区间:

  • 移除0个空格:1种结果(原字符串)
  • 移除1个连续空格:4种结果
  • 移除2个连续空格:3种结果
  • 移除3个连续空格:2种结果
  • 移除4个连续空格:1种结果
    总计11种,和示例数量完全匹配。
    实现时按「连续移除空格的长度从小到大、同长度下移除区间从左到右」的顺序枚举,即可生成和示例顺序一致的结果。
可运行完整代码
function getAllWordCombinations(str) {
  const words = str.split(' ').filter(Boolean);
  const totalSpaces = words.length - 1;
  const result = [];

  // 枚举连续移除的空格数量,从0(不移除)到总空格数(全移除)
  for (let removeSpaceCount = 0; removeSpaceCount <= totalSpaces; removeSpaceCount++) {
    // 枚举连续移除空格段的起始位置
    for (let rangeStart = 0; rangeStart <= totalSpaces - removeSpaceCount; rangeStart++) {
      const rangeEnd = rangeStart + removeSpaceCount;
      const parts = [];
      let wordIndex = 0;
      while (wordIndex < words.length) {
        if (wordIndex === rangeStart) {
          // 合并空格段覆盖的所有单词
          let mergedWord = '';
          for (let m = rangeStart; m <= rangeEnd + 1; m++) {
            mergedWord += words[m];
          }
          parts.push(mergedWord);
          wordIndex = rangeEnd + 2;
        } else {
          parts.push(words[wordIndex]);
          wordIndex++;
        }
      }
      result.push(parts.join(' '));
    }
  }
  return result;
}

// 测试用例
const inputStr = 'test string of whole words';
const combinationResult = getAllWordCombinations(inputStr);
combinationResult.forEach(item => console.log(item));

运行上述代码即可得到全部预期结果。

内容的提问来源于stack exchange,提问作者Pankaj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:45:34