LeetCode周賽#111 Q3 DI String Match
阿新 • • 發佈:2018-11-26
題目來源: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"
, 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 <= 10000
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;
}
};