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 <= text.length <= 1000textconsists 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)

本文介绍了一种算法,用于找出字符串中包含所有不同字符且字典序最小的子序列。通过实例展示如何从给定的字符串中选取唯一字符构成最小字典序子序列,如cdadabcc->adbc。算法使用了计数器和集合来跟踪字符频率和已用字符,递归地构建最小子序列。

282

被折叠的 条评论
为什么被折叠?



