找到一个跟我的思路比较接近的参考解决方案:
1 class Solution: 2 def smallestSubsequence(self, text: str) -> str: 3 n = len(text) 4 d = collections.defaultdict(collections.deque) 5 # record index 6 for i,v in enumerate(text): 7 d[ord(v)-ord('a')].append(i) 8 9 # search orderly 10 keys = sorted(d.keys()) 11 res = [] 12 c = len(d) 13 last_index = -1 14 while len(res) < c: # len(res) will not larger than 26 15 # O(26*26) time, search the first smallest letter 16 for i in range(len(keys)): 17 if all(d[keys[i]][0] < d[keys[j]][-1] for j in range(i+1, len(keys))): 18 res.append(chr(ord('a')+keys[i])) 19 last_index = d[keys[i]][0] 20 keys.remove(keys[i]) 21 break 22 # O(n) time, delete all index less than last_index 23 for i in range(len(keys)): 24 while d[keys[i]] and d[keys[i]][0] < last_index: 25 d[keys[i]].popleft() 26 27 return ''.join(res)