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

  • 相关阅读:
    利用@media screen实现网页布局的自适应
    js判断手机的左右滑动
    文档流
    对文本段落操作的一些细节
    简易菜单的制作
    jQuery Scroll Follow
    node 监听接口
    浏览器通知
    webSocket
    前端学习路线
  • 原文地址:https://www.cnblogs.com/sxuer/p/10643380.html
Copyright © 2020-2023  润新知