zoukankan      html  css  js  c++  java
  • 【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]

    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的位置一定能放当前能放的元素中最大的那个。所以遍历S,如果是I,放入当前的最小值,同时最小值加一;如果是D,放入当前的最大值,同时最大值减一。

    代码如下:

    class Solution(object):
        def diStringMatch(self, S):
            """
            :type S: str
            :rtype: List[int]
            """
            low = 0
            high = len(S)
    
            res = []
            for i in S:
                if i == 'I':
                    res.append(low)
                    low += 1
                else:
                    res.append(high)
                    high -= 1
            res.append(low)
            return res
  • 相关阅读:
    50个网页常用小代码
    web前端题目(持续更新)
    一步步构建大型网站架构(转)
    CentOS下配置node.js
    ajax文件上传
    test
    文件上传input简便美化方案
    String.match()与RegExp.exec()
    ie7下zindex问题
    javascript将数组插入到另一个数组中
  • 原文地址:https://www.cnblogs.com/seyjs/p/9982826.html
Copyright © 2011-2022 走看看