1. 程式人生 > >LeetCode周賽#111 Q3 DI String Match

LeetCode周賽#111 Q3 DI String Match

題目來源:https://leetcode.com/contest/weekly-contest-111/problems/di-string-match/

問題描述

 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]

 

Note:

  1. 1 <= S.length <= 10000
  2. S only contains characters "I" or "D".

------------------------------------------------------------

題意

規定一個長度為N,由”I”和”D”組成的字元陣列S,對應一個由0~N組成的N+1位整數陣列A,S[i] = ”I”代表A[i] < A[i+1], S[i] = “D”代表A[i] > A[i+1]. 給定S,求任意一個符合規定的A.

------------------------------------------------------------

思路

S[i] = 第ni個‘I’對應A[i] = ni, S[i] = 第nd個‘D’對應A[i] = N-nd.

------------------------------------------------------------

程式碼

class Solution {
public:
    vector<int> diStringMatch(string S) {
        int n = S.size(), i = 0, cnti = 0, cntd = 0;
        int * v = new int[n+1];
        for (i=0; i<n; i++)
        {
            if (S[i] == 'I')
            {
                v[i] = cnti;
                cnti++;
            }
            else
            {
                v[i] = n - cntd;
                cntd++;
            }
        }
        v[n] = cnti;
        vector<int> V(v, v+n+1);
        delete[] v;
        return V;
    }
};