LeetCode题解(1081):不同字符的最小子序列(Python)
发布日期:2021-06-29 19:58:22 浏览次数:4 分类:技术文章

本文共 988 字,大约阅读时间需要 3 分钟。

题目:(中等)

标签:贪心算法、栈、字符串

相关题目:与题目316相同

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1) 108ms (6.50%)
Ans 2 (Python) O ( N ) O(N) O(N) O ( 1 ) O(1) O(1) 40ms (95.53%)
Ans 3 (Python)

解法一(贪心算法):

class Solution:    def smallestSubsequence(self, s: str) -> str:        if not s:            return ""        count = collections.Counter(s)        pos = 0        for i in range(len(s)):            if s[i] < s[pos]:                pos = i            count[s[i]] -= 1            if count[s[i]] == 0:                break        return s[pos] + self.smallestSubsequence(s[pos:].replace(s[pos], ""))

解法二(用栈维护最小字典序结果):

class Solution:    def smallestSubsequence(self, s: str) -> str:        count = collections.Counter(s)        stack = []        for ch in s:            count[ch] -= 1            if ch not in stack:                while stack and stack[-1] > ch and count[stack[-1]] > 0:                    stack.pop()                stack.append(ch)        return "".join(stack)

转载地址:https://dataartist.blog.csdn.net/article/details/108092024 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(1096):按照指定语法展开字符串的花括号(Python)
下一篇:LeetCode题解(1023):判断字符串是否能通过模式串添加小写字母生成(Python)

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月24日 08时13分42秒