forked from trekhleb/javascript-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutateString.js
More file actions
35 lines (28 loc) · 1.11 KB
/
permutateString.js
File metadata and controls
35 lines (28 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
export default function permutateString(str) {
if (str.length === 0) {
return [];
}
if (str.length === 1) {
return [str];
}
const permutations = [];
// Get all permutations of string of length (n - 1).
const previousString = str.substring(0, str.length - 1);
const previousPermutations = permutateString(previousString);
// Insert last character into every possible position of every previous permutation.
const lastCharacter = str.substring(str.length - 1);
for (
let permutationIndex = 0;
permutationIndex < previousPermutations.length;
permutationIndex += 1
) {
const currentPermutation = previousPermutations[permutationIndex];
// Insert strLastCharacter into every possible position of currentPermutation.
for (let positionIndex = 0; positionIndex <= currentPermutation.length; positionIndex += 1) {
const permutationPrefix = currentPermutation.substr(0, positionIndex);
const permutationSuffix = currentPermutation.substr(positionIndex);
permutations.push(permutationPrefix + lastCharacter + permutationSuffix);
}
}
return permutations;
}