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 <= 1000
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)