LeetCode题解(1047):删除字符串中的所有相邻重复项(Python)
发布日期:2021-06-29 19:55:20 浏览次数:3 分类:技术文章

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

题目:(简单)

标签:字符串、字符串-替换函数、栈、正则表达式、正则表达式-替换函数

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N ) O(N) O(N) O ( N ) O(N) O(N) 104ms (35.00%)
Ans 2 (Python) O ( N 2 ) O(N^2) O(N2) O ( N ) O(N) O(N) 56ms (99.29%)
Ans 3 (Python) O ( N ) O(N) O(N) 56ms (99.29%)

LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。

解法一(栈):

def removeDuplicates(self, S: str) -> str:    stack = []    for s in S:        if len(stack) == 0 or stack[-1] != s:            stack.append(s)        else:            stack.pop(-1)    return "".join(stack)

解法二(替换函数):

def removeDuplicates(self, S: str) -> str:    duplicates = {
2 * ch for ch in string.ascii_lowercase} last_length = -1 while len(S) != last_length: last_length = len(S) for d in duplicates: S = S.replace(d, "") return S

解法三(正则表达式):

def removeDuplicates(self, S: str) -> str:    last_length = -1    while len(S) != last_length:        last_length = len(S)        S = re.sub(r"(.)\1", "", S)    return S

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

上一篇:LeetCode题解(1051):生成非递减顺序排列的最小移动人数(Python)
下一篇:LeetCode题解(1046):最后一块石头的重量(Python)

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2024年04月14日 02时06分26秒