JavaScript 如何生成字符串的所有组合
在本文中,我们将看看是否可以使用JavaScript方法或概念生成给定字符串的所有可能组合。
给定一个包含不同字符的字符串,您需要通过一次选择一个字符,然后重新排列该字符与其他字符,以便可以生成和轻松输出所有组合的字符串。
解决这个特定问题有几种方法,我们将逐一讨论每一种方法,但首先,让我们明确我们需要实现什么。
以下图示描述了生成给定字符串的所有可能组合的情景。
Dog => Possible Combination [D], [Do], [Dog], [o], [og], [g]
作为一个例子(在上面的图片中提到),一个名为“ Dog”的字符串可以被进一步拆分成多个字符串,如“ D”,“ Do”等等。 以下是用JavaScript生成字符串所有组合的几种方法: - 使用.push() 和 .slice() 方法 - 使用.charAt() 和 .concat() 方法 - 使用for循环和.push() 方法
方法1:使用.push() 和 .slice() 方法
在这种方法中,我们将使用一个名为数组的数据结构,并在给定字符串上运行两个for循环,这实际上是我们代码的主要逻辑部分。 此外,我们将使用.push() 和 .slice() 方法将结果添加到数组中。
示例: 这个示例展示了上述方法的使用。
let possibleCombinations = (str) => {
let combinations = [];
for (let i = 0; i < str.length; i++) {
for (let j = i + 1; j < str.length + 1; j++) {
combinations.push(str.slice(i, j));
}
}
return combinations;
}
console.log(possibleCombinations('Dog'));
输出: 上述程序的输出将如下所示。
[ 'd', 'do', 'dog', 'o', 'og', 'g' ]
方法2:使用.charAt()和.concat()方法
- 在这个方法中,我们将再次使用一个数组作为我们的结果打印变量,并且我们将取我们当前索引值作为起始值(即0)。
- 然后我们将运行一个while循环,在该循环中我们将使用.charAt()方法存储我们当前索引值处的字符。
- 然后我们将声明一个临时数组,在该数组中存储所得到的字符。
- 然后我们将运行一个for-in循环,在其中我们将推入我们的结果,然后我们将使用.concat()方法将我们的结果添加到结果变量中,并且我们将增加我们当前索引变量的值。
示例: 这个例子展示了以上解释的方法的使用。
let stringCombinations = (str) => {
let strLength = str.length;
let result = [];
let currentIndex = 0;
while (currentIndex < strLength) {
let char = str.charAt(currentIndex);
let x;
let arrTemp = [char];
for (x in result) {
arrTemp.push("" + result[x] + char);
}
result = result.concat(arrTemp);
currentIndex++;
}
return result;
};
console.log(stringCombinations("dog"));
输出: 以上代码的输出结果如下。
[ 'd', 'o', 'do', 'g', 'dg', 'og', 'dog' ]
方法3:使用for循环和.push()方法
- 在这种方法中,我们将使用两个数组,其中一个是临时数组,它将最初存储我们的结果,并在最后将结果添加到第二个结果数组中。
- 在这里,我们首先将使用一个for循环,然后在该循环的内部,我们将使用另一个for循环,将字符串的每个字符添加到临时数组中,并以0作为起始索引值。
- 然后,在for循环的内部,我们将使用 .push() 方法将结果推到临时数组中,并增加当前索引值。
- 然后在for循环之后,我们将从临时数组中将结果添加到我们的结果数组中,然后打印结果数组。
示例:
let combinations = (str) => {
let tempArr = [];
let resultArr = [];
for (let i = 0; i < str.length; i++) {
tempArr = [str[i]];
let index = 0;
while (resultArr[index]) {
tempArr.push("" + resultArr[index] + str[i]);
index++;
}
resultArr = resultArr.concat(tempArr);
}
return resultArr;
};
console.log(combinations("dog"));
输出
[
'd', 'o',
'do', 'g',
'dg', 'og',
'dog'
]