• 9. DI String Match


    Title:

    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]

    Note:

    1. 1 <= S.length <= 10000
    2. S only contains characters "I" or "D".

    Analysis of Title:

    If S[i] == "I", then A[i] < A[i+1]  It means when get a 'I' then in here is a smaller and the next is bigger.

    If S[i] == "D", then A[i] > A[i+1]  In the similar way.

    Test case:

    "IDID"

    Python:

    ps: A simple way is "for : If I then get 0,0+1; If D then get len(S),len(S)-1"

    But I want to learn another method of deque.

    class Solution(object):
      def diStringMatch(self, S):
      """
      :type S: str
      :rtype: List[int]
      """
      from collections import deque

      table = deque(range(len(S)+1)) #创建双端队列可迭代对象,数据包括 0~len(S)+1
      res = []
      for s in S:
        if s=='I':
          res.append(table.popleft()) #若为I,加入左边(小)
        else:
          res.append(table.pop()) #若为D,加入右边(大)
      res.append(table.pop()) #把最后一个加进去,输出比输入多一位
      return res

    Analysis of Code:

    All the analysis is already in the Title.

  • 相关阅读:
    pwdLastSet AD
    快递条形码类型
    Sharepoint 应用程序池自动停止
    Visual Studio 2015安装后“无法启动iis express web 服务器”
    Knockout自定义绑定数据逻辑
    Knockout基本绑定数据
    TableAttribute同时存在于
    微服务架构下的鉴权,怎么做更优雅?
    使用 Yopto 插件给商品添加评论
    Docker 基本概念
  • 原文地址:https://www.cnblogs.com/sxuer/p/10643380.html
Copyright © 2020-2023  润新知