Leetcode-Easy 942. DI String Match

简介: Leetcode-Easy 942. DI String Match

题目描述


给定仅包含“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]

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]


思路


  • 我们可以用的数字是一个整数数组[0,1,2,...,len(S)]
  • 当看到“I”时,最安全的选择就是为下次移动设置最低(最左边)的数字,所以它总会增加
  • 当看到“D”时,最安全的选择是为下次移动放置最高(最右边)的数字,所以它总会减少
  • 最后放入当lo==hi的数字


代码实现


class Solution:
    def diStringMatch(self, S: 'str') -> 'List[int]':
        lo,hi=0,len(S)
        ans=[]
        for x in S:
            if x=='I':
                ans.append(lo)
                lo+=1
            if x=='D':
                ans.append(hi)
                hi-=1
        return ans+[hi]
        # return ans+[hi] 和上语句同样效果,此时lo==hi


思路来自:https://leetcode.com/problems/di-string-match/solution/


其实我们发现返回的结果不一定是唯一的,例如S='IDID'时,我们方法得出的结果是[0,4,1,3,2],但是像[1,4,0,3,2],[0,4,2,3,1]也是符合题意的。这个思路可以理解是贪婪算法,然后我们每次求的都是最优解。


相关文章
|
7月前
|
算法 C++
【LeetCode】【C++】string OJ必刷题
【LeetCode】【C++】string OJ必刷题
36 0
|
2月前
|
机器学习/深度学习 canal NoSQL
从C语言到C++_12(string相关OJ题)(leetcode力扣)
从C语言到C++_12(string相关OJ题)(leetcode力扣)
31 0
|
2月前
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
8月前
|
Java
Leetcode 467. Unique Substrings in Wraparound String
大概翻译下题意,有个无限长的字符串s,是由无数个「abcdefghijklmnopqrstuvwxy」组成的。现在给你一个字符串p,求多少个p的非重复子串在s中出现了?
30 0
|
算法 索引
【LeetCode】string 类的几道简单题
【LeetCode】string 类的几道简单题
【LeetCode】string 类的几道简单题
LeetCode 438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter.
67 0
LeetCode 438. Find All Anagrams in a String
|
存储
LeetCode 394. Decode String
给定一个经过编码的字符串,返回它解码后的字符串。 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
68 0
LeetCode 394. Decode String
|
索引
LeetCode 387. First Unique Character in a String
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
88 0
LeetCode 387. First Unique Character in a String
|
索引
LeetCode 345. Reverse Vowels of a String
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
59 0
LeetCode 345. Reverse Vowels of a String
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
76 0
LeetCode 344. Reverse String