LeetCode 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", then A[i] < A[i+1]
  • If S[i] == "D",then A[i] > A[i+1]

题目分析及思路

题目给出一个只包含I或D的字符串,要求返回一个序列,序列长度为字符串长度N+1。当字母为I,则序列的对应位置比后面位置的值要大;若字母为D,则相反。我们可以使第一个出现I的位置对应的是0,第一个D出现的位置对应的是N,那么无论这个位置后面出现的是另外的哪个数字,当前的位置都能满足题设条件。我们每次遇见I都比之前的I增加1,每次遇到D都比之前的D减小1。这样会尽可能的给后面的数字让出空间。

python代码​

class Solution:

    def diStringMatch(self, S):

        """

        :type S: str

        :rtype: List[int]

        """

        N = len(S)

        min,max = 0,N

        res = list()

        for s in S:

            if s == 'I':

                res.append(min)

                min = min + 1

            if s == 'D':

                res.append(max)

                max = max - 1

        res.append(min)

        return res

                

        

        

 

posted on 2019-01-10 14:39  锋上磬音  阅读(92)  评论(0编辑  收藏  举报