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"
.
题意:给定一个字符串只包括,I和D,其中I表示增加,D表示减少,设串长N,让你用0-N这些数字组成一个序列,满足字符串给定的关系。
思路:基于贪心思想,令mn表示当前能选择的最小数(初始0),mx表示当前能选择的最大数(初始N),
每次遇到 ‘I’ 就令当前最小数mn入队列,然后最小数加一,
每次遇到 ‘D’ 就令当前最大数mx入队列,然后最大数减一,遍历完成即可得到答案。
这样所有的I对应数满足递增关系,所有D对应数满足递减关系,并且D对应的数均大于I对应的数。
参考代码:
class Solution {
public:
vector<int> diStringMatch(string S) {
int mn=0,mx=S.size();
vector<int> ans;
for(int i=0;i<S.size();i++){
if(S[i]=='I'){
ans.push_back(mn);
mn++;
}else{
ans.push_back(mx);
mx--;
}
}
ans.push_back(mn);
return ans;
}
};