leetcode1081. Smallest Subsequence of Distinct Characters
Posted seyjs
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1081. Smallest Subsequence of Distinct Characters相关的知识,希望对你有一定的参考价值。
题目如下:
Return the lexicographically smallest subsequence of
text
that contains all the distinct characters oftext
exactly once.
Example 1:
Input: "cdadabcc" Output: "adbc"
Example 2:
Input: "abcd" Output: "abcd"
Example 3:
Input: "ecbacba" Output: "eacb"
Example 4:
Input: "leetcode" Output: "letcod"
Note:
1 <= text.length <= 1000
text
consists of lowercase English letters.
解题思路:首先找出每个字母在text中的最大下标值并存入inx列表,接下来把text中的出现的每个字母的存入list并排好序:如果list[0]的字母在text中小标的最小值小于或者inx中所有元素的最小值,则表示该字母可以放在结果的第一个位置;如果不行则继续检查list[1]的字母,直到找出符合条件的字母放在第一位,然后在inx和list中删掉这个字母所对应的记录。之后继续循环查找,直到所有字母都找到为止。
代码如下:
class Solution(object): def smallestSubsequence(self, text): """ :type text: str :rtype: str """ dic = for i in range(len(text)-1,-1,-1): if text[i] not in dic: dic[text[i]] = i tl = sorted(dic.iterkeys()) res = ‘‘ start = 0 while len(tl) > 0: for i in range(len(tl)): inx = text.find(tl[i],start) if inx <= min(dic.itervalues()): res += tl[i] start = inx + 1 del dic[tl[i]] del tl[i] break return res
以上是关于leetcode1081. Smallest Subsequence of Distinct Characters的主要内容,如果未能解决你的问题,请参考以下文章
908. Smallest Range I - LeetCode
Leetcode 230. Kth Smallest Element in a BST
Leetcode 230. Kth Smallest Element in a BST
LeetCode Find K Pairs with Smallest Sums