942. DI String Match
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]
My code
class Solution {
public int[] diStringMatch(String S) {
int f=0,e=S.length();
int[] A = new int[e+1];
int i;
for(i=0;i<S.length();i++){
A[i]= S.charAt(i)=='I'?f++:e--;
}
A[i]= S.charAt(i-1)=='I'?f:e;
return A;
}
}
思路
题目让我们根据字符串内容返回一个数组,根据所给例子,我们得知数组大小比字符串长度多1,而且数组元素最大的数字为字符串长度大小,最小为0;可以看出规律:当前 “I” 的数字比下一个 “I” 的数字小1,而“D” 则是相反。
循环完之后,数组还剩1空位没有元素,因此还需要再判断字符串最后一个元素来决定数组最后一个数字是什么。