[LeetCode] 942. DI String Match

Easy

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".

题目大意:给定一个字符串,字符串中只包含I或者D,I表示上升,D表示下降。令N=S.length。返回一个数组A,数组A中的元素是0~N中的所有数字,并且数字的排序方式符合S中给出的指示。

比如:S中的第一个字母表示A[0]到A[1]的跳跃关系,S中的第一个字母是I,那么A[0]<A[1],第二个字母是D,那么A[1]>A[2],以此类推。

观察给出的三个例子发现,在选择当前数字时应尽量给下次升或降留下更多的余地,也就是从当前数字到下一个数字是I时,就要让当前数字尽可能小,给升高留足够空间,以至能不重复的使用0~N中的数字。

最后剩下的一个数字直接放在最后就好了。

我们可以使用两个变量start和end来表示当前剩下的数字的范围。每次使用其中的数字后都更新可使用数字范围。

代码如下:

class Solution {
public:
    vector<int> diStringMatch(string S) {
        vector<int> res;
        int len=S.size();
        int start=0,end=len;
        
        for(int i=0;i<len;++i){
            if(S[i]=='I'){
                res.push_back(start);
                start++;
            }
            else if(S[i]=='D'){
                res.push_back(end);
                end--;
            }
        }
        res.push_back(end);
        return res;
    }
};
原文地址:https://www.cnblogs.com/cff2121/p/11446435.html