1. 程式人生 > >LeetCode 942. 增減字串匹配(C、C++、python)

LeetCode 942. 增減字串匹配(C、C++、python)

給定只含 "I"(增大)或 "D"(減小)的字串 S ,令 N = S.length

返回 [0, 1, ..., N] 的任意排列 A 使得對於所有 i = 0, ..., N-1,都有:

  • 如果 S[i] == "I",那麼 A[i] < A[i+1]
  • 如果 S[i] == "D",那麼 A[i] > A[i+1]

 

示例 1:

輸出:"IDID"
輸出:[0,4,1,3,2]

示例 2:

輸出:"III"
輸出:[0,1,2,3]

示例 3:

輸出:"DDI"
輸出:[3,2,0,1]

 

提示:

1 <= S.length <= 1000

S 只包含字元 "I" 或 "D"

C

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* diStringMatch(char* S, int* returnSize) 
{
    int N=strlen(S);
    int* res=(int*)malloc(sizeof(int)*(N+1));
    int a=N;
    int b=0;
    for(int i=0;i<N;i++)
    {
        if('I'==S[i])
        {
            res[i]=b;
            b++;
        }
        else
        {
            res[i]=a;
            a--;
        }
    }
    res[N]=b;
    *returnSize=N+1;
    return res;
}

C++

class Solution {
public:
    vector<int> diStringMatch(string S) 
    {
        int N=S.length();
        int a=N;
        int b=0;
        vector<int> res(N+1,0);
        for(int i=0;i<N;i++)
        {
            if('I'==S[i])
            {
                res[i]=b;
                b++;
            }
            else
            {
                res[i]=a;
                a--;
            }
        }
        res[N]=a;
        return res;        
    }
};

python

class Solution:
    def diStringMatch(self, S):
        """
        :type S: str
        :rtype: List[int]
        """
        N=len(S)
        res=[0 for i in range(N+1)]
        a=N
        b=0
        for i in range(N):
            if 'I'==S[i]:
                res[i]=b
                b+=1
            else:
                res[i]=a
                a-=1
        res[N]=a
        return res