316. Remove Duplicate Letters [Hard] 去重保留字典序

316. Remove Duplicate Letters

316. Remove Duplicate Letters [Hard] 去重保留字典序_第1张图片
316. Remove Duplicate Letters

阿里面试题,需要用到栈,还要记录出现次数,以及是否已经用过

class Solution(object):
    def removeDuplicateLetters(self, s):
        """
        :type s: str
        :rtype: str
        """
        isVisited = set()
        stack = []
        dic = {}
        for i in s:
            if i in dic:
                dic[i] += 1
            else:
                dic[i] = 1
        for i in s:
            if i in isVisited:
                dic[i] -= 1
                continue
            if stack == [] or stack[-1] < isVisited:
                stack.append(i)
                isVisited.add(i)
                dic[i] -= 1
            else:
                while stack and stack[-1] > i and dic[stack[-1]] > 0:
                    a = stack.pop()
                    isVisited.remove(a)
                stack.append(i)
                isVisited.add(i)
                dic[i] -= 1
        return ''.join(stack)

你可能感兴趣的:(316. Remove Duplicate Letters [Hard] 去重保留字典序)