484. Find Permutation π
Description
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'ifperm[i] < perm[i + 1], ands[i] == 'D'ifperm[i] > perm[i + 1].
Given a string s, reconstruct the lexicographically smallest permutation perm and return it.
Example 1:
Input: s = "I" Output: [1,2] Explanation: [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
Example 2:
Input: s = "DI" Output: [2,1,3] Explanation: Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
Constraints:
1 <= s.length <= 105s[i]is either'I'or'D'.
Solutions
Solution 1
Thinking
Build the lexicographically smallest permutation of \(1..n+1\) matching an \(I/D\) string. Smallest order wants an increasing sequence except where a descent is required.
Start from \(1,2,\ldots,n+1\) and reverse each segment that a run of \(D\) covers. Positions with \(I\) keep their relative order.
Reversing a \(D\)-run makes that interval decreasing and does not enlarge an untouched prefix, so the permutation is the smallest one.
1 2 3 4 5 6 7 8 9 10 11 12 | |
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 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |