码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode1080

时间:2019-06-09 22:25:27      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:pop   think   leetcode   code   RoCE   enum   last   remove   for   

找到一个跟我的思路比较接近的参考解决方案:

 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)

参考:https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/discuss/308222/show-my-thinking-process

leetcode1080

标签:pop   think   leetcode   code   RoCE   enum   last   remove   for   

原文地址:https://www.cnblogs.com/asenyang/p/10995035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!