A permutation perm
of n + 1
integers of all the integers in the range [0, n]
can be represented as a string s
of length n
where:
s[i] == 'I'
ifperm[i] < perm[i + 1]
, ands[i] == 'D'
ifperm[i] > perm[i + 1]
.
Given a string s
, reconstruct the permutation perm
and return it. If there are multiple valid permutations perm, return any of them.
Example 1:
Input: s = "IDID" Output: [0,4,1,3,2]
Example 2:
Input: s = "III" Output: [0,1,2,3]
Example 3:
Input: s = "DDI" Output: [3,2,0,1]
Constraints:
1 <= s.length <= 105
s[i]
is either'I'
or'D'
.
题目给描述的好复杂……其实就是把string变成0 - n的数字,I就是当前的比后面的小,D就是当前的比后面的大,那就直接遇到I就放最小的,遇到D就放最大的就完事了。
class Solution {
public int[] diStringMatch(String s) {
int n = s.length();
int small = 0;
int large = n;
int[] result = new int[n + 1];
int i = 0;
for (char c : s.toCharArray()) {
if (c == 'I') {
result[i] = small;
small++;
} else {
result[i] = large;
large--;
}
i++;
}
result[i] = small;
return result;
}
}