316. Remove Duplicate Letters
题干:
Given a string which contains only lowercase letters, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results.
解释:
给一个字符串,要求删掉所有重复字符,保持字典序最小
思考:
题目非常直白,去掉重复也很容易,难点在于如何保持字典序最小。所以我的想法是用滑动窗口来做,在维持包含所有字母的情况下更新字典序最小的子序列。看了答案恍然大悟,其实这个题用py做最快,因为只要发现有比栈顶元素字典序小,然后栈顶元素后面还有,就可以直接替换,这样就保持了字典需最大了。厉害
答案:
class Solution:
def removeDuplicateLetters(self, s: str) -> str:
mid_list = ["0"]
for index, alpha in enumerate(s):
if alpha not in mid_list:
while alpha < mid_list[-1] and s[index:].count(mid_list[-1]) > 0:
mid_list.pop(-1)
mid_list.append(alpha)
return "".join(mid_list[1:])