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;
    }
}
posted on 2019-03-19 21:22  王 帅  阅读(57)  评论(0编辑  收藏  举报