https://leetcode.com/contest/weekly-contest-111/problems/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"
, thenA[i] < A[i+1]
- If
S[i] == "D"
, thenA[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 <= 1000
S
only contains characters"I"
or"D"
.
/**
* 本题思路:从中间位置考虑,若需要增加则向后取一个数,反之则向前取数。
* 另外,还要考虑I和D的数量关系,以此来确定从何处开始
/
public int[] diStringMatch(String S) {
int[] res = new int[S.length()+1];
List<Integer> nums = new ArrayList<>();
for (int i = 0; i <= S.length(); i++) {
nums.add(i);
}
//统计I和D的数目
int ic = 0, dc = 0;
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'I') {
ic++;
} else {
dc++;
}
}
//若I和D的数目相等,则从中间位置开始;相差多少,就从中间偏移多少
int cur = (nums.size() - (ic-dc))/2;
//正向偏移和负向偏移
int pOffset=0 , nOffset=0;
int p = 0;
res[p++] = nums.get(cur);
for (int i = 0; i < S.length(); i++) {
if (S.charAt(i) == 'I') {
//若遇见I,则向后取一个数
res[p++] = nums.get(cur+(++pOffset));
} else if (S.charAt(i) == 'D') {
若遇见D,则向前取一个数
res[p++] = nums.get(cur+(--nOffset));
}
}
return res;
}