-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path0484-find-permutation.js
More file actions
39 lines (36 loc) · 956 Bytes
/
0484-find-permutation.js
File metadata and controls
39 lines (36 loc) · 956 Bytes
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
36
37
38
39
/**
* 484. Find Permutation
* https://leetcode.com/problems/find-permutation/
* Difficulty: Medium
*
* A permutation perm of n integers of all the integers in the range [1, n] can be
* represented as a string s of length n - 1 where:
* - s[i] == 'I' if perm[i] < perm[i + 1], and
* - s[i] == 'D' if perm[i] > perm[i + 1].
*
* Given a string s, reconstruct the lexicographically smallest permutation perm and return it.
*/
/**
* @param {string} s
* @return {number[]}
*/
var findPermutation = function(s) {
const n = s.length + 1;
const result = new Array(n).fill(0).map((_, i) => i + 1);
for (let i = 0; i < s.length; i++) {
if (s[i] === 'D') {
let start = i;
while (i < s.length && s[i] === 'D') {
i++;
}
let end = i;
while (start < end) {
[result[start], result[end]] = [result[end], result[start]];
start++;
end--;
}
i--;
}
}
return result;
};