942. DI String Match
Keep two int variable to record min and max value, when encounter I, use max++ value, on the contrary, use min--.
At last, add - (min + 1) to all elements of result array.
class Solution {
public int[] diStringMatch(String S) {
int[] ret = new int[S.length() + 1];
ret[0] = 0;
int min = -1, max = 1;
for (int i = 0; i < S.length(); ++i) {
if (S.charAt(i) == 'I') {
ret[i + 1] = max++;
}
else {
ret[i + 1] = min--;
}
}
min = -(min + 1);
for (int i = 0; i < ret.length; ++i) ret[i] += min;
return ret;
}
}