题目来源: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;
}
};