版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85727563
Title: DI String Match 942
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/di-string-match/
1. 见代码注释
时间复杂度:O(n),两次一层for循环。
空间复杂度:O(n),申请额外空间数组,最后需要返回这个数组。
/**
* 假设需要求解的数组递增,将遇到D时,将其对应的位置赋最大值,后面遇到D,依次减一,最后将没有赋值的数组的位置从0开始赋值
* @param S
* @return
*/
public static int[] diStringMatch(String S) {
int n = S.length() + 1;
int res[] = new int[n];
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'D') {
res[i] = --n;
}
}
int k = 0;
for (int i = 0; i < res.length; i++) {
if (res[i] == 0) {
res[i] = k++;
}
}
return res;
}