Given a string S that only contains “I” (increase) or “D” (decrease), let N = S.length.
Return any permutation A of [0, 1, …, N] such that for all i = 0, …, N-1:
If S[i] == "I", then A[i] < A[i+1]
If S[i] == "D", then A[i] > A[i+1]Example 1:
Input: “IDID” Output: [0,4,1,3,2]
Example 2:
Input: “III” Output: [0,1,2,3]
Example 3:
Input: “DDI” Output: [3,2,0,1]
Note:
1 <= S.length <= 10000
S only contains characters "I" or "D".题意:给一串字符串,只包含I和D,I表示下一个数字是升序的,D表示下一个数字是降序的。 数组长度比字符串长度多一(数组最大值=字符串长度),数组数字必须是按顺序被使用的自然数(比如字符串长度为3,则数组只能用(0,1,2,3)之中的数字)
这道题难就难在,规律难找。
算法: 每个数只能被使用一次,最小为0,最大为S.length; 如果当前为I(升),则为0++,如果当前为D(降),则为S.length–; 将最后一位置为0++之后的值
class Solution {
public int[] diStringMatch(String S) {
int N = S.length();
int lo = 0, hi = N;
int[] ans = new int[N + 1];
for (int i = 0; i < N; ++i) {
if (S.charAt(i) == 'I')
ans[i] = lo++;
else
ans[i] = hi--;
}
ans[N] = lo;
return ans;
}
}