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]

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]

解答

這道題可以找規律,當遇到I的時候,插入一個數字比右邊的小,當遇到D的時候,插入一個數字比右邊的大。又同時因爲,數字只能是0到N之間,所以可以做出一個想法。

當遇到I的時候插入可用的,最小的一個數,最開始是0,如果0被佔用了,就插入1,不重複,且最小。D則相反,插入不重複的,最大的一個數,從S.length()開始。

class Solution {
    public int[] diStringMatch(String S) {
        int[] a = new int[S.length() + 1];

        int writeIntWhenD = S.length();
        int writeIntWhenI = 0;

        for (int i = 0; i < S.length(); i++) {
            if (S.charAt(i) == 'I') {
                a[i] = writeIntWhenI;
                writeIntWhenI++;
                if (i == S.length() - 1) {
                    a[i + 1] = a[i] + 1;
                }
            } else {
                a[i] = writeIntWhenD;
                writeIntWhenD--;
                if (i == S.length() - 1) {
                    a[i + 1] = a[i] - 1;
                }
            }
        }

        return a;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章