题目如下:
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
原文地址:https://www.cnblogs.com/seyjs/p/11026152.html
时间: 2024-10-09 12:17:29