5086. Smallest Subsequence of Distinct Characters

42 篇文章 0 订阅
26 篇文章 0 订阅

Return the lexicographically smallest subsequence of text that contains all the distinct characters of text 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. 1 <= text.length <= 1000
  2. text consists of lowercase English letters.

思路:从左往右遍历,当遍历到某个char出现这种情况时停下来:后面不再出现某个char。(这时候必须要要在前面这些char作出选择)

然后前面部分取出最小的char,然后继续递归

from collections import Counter
class Solution(object):
    def smallestSubsequence(self, text):
        """
        :type text: str
        :rtype: str
        """
        if not text: return ''
        d=Counter([s for s in text])
        used=set()
        for s in text:
            used.add(s)
            d[s]-=1
            if d[s]==0: break
        ls=sorted(list(used))
        left=text[text.index(ls[0]):].replace(ls[0], '')
        return ls[0]+self.smallestSubsequence(left)
    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值