题目地址:
https://www.lintcode.com/problem/find-permutation/description
给定一个只含 I I I和 D D D的长 n − 1 n-1 n−1的字符串 s s s。要求返回一个恰好含 1 ∼ n 1\sim n 1∼n的长 n n n的数组 t t t,使得 s [ i ] = I ⇔ t [ i + 1 ] > t [ i ] s[i]=I\Leftrightarrow t[i+1]>t[i] s[i]=I⇔t[i+1]>t[i],且 s [ i ] = D ⇔ t [ i + 1 ] < t [ i ] s[i]=D\Leftrightarrow t[i+1]<t[i] s[i]=D⇔t[i+1]<t[i]。返回符合要求的字典序最小的数组。
参考https://blog.csdn.net/qq_46105170/article/details/111027516。代码如下:
public class Solution {
/**
* @param s: a string
* @return: return a list of integers
*/
public int[] findPermutation(String s) {
// write your code here
int[] res = new int[s.length() + 1];
for (int i = 0; i < res.length; i++) {
res[i] = i + 1;
}
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'D') {
int j = i;
while (j < s.length() && s.charAt(j) == 'D') {
j++;
}
reverse(res, i, j);
i = j;
}
}
return res;
}
private void reverse(int[] A, int i, int j) {
for (; i < j; i++, j--) {
int tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
}
时间复杂度 O ( n ) O(n) O(n)。