0
点赞
收藏
分享

微信扫一扫

LeetCode题解(1003):检查字符串是否由指定字符串拼接产生(Python)


题目:​​原题链接​​(中等)

标签:字符串、栈

解法

时间复杂度

空间复杂度

执行用时

Ans 1 (Python)

O(N)

36ms (99.03%)

Ans 2 (Python)

O(N)

O(N)

56ms (59.42%)

Ans 3 (Python)

解法一(字符串替换):

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gCCEjMgV-1596690366521)(LeetCode题解(1003)]:截图1.png)

def isValid(self, S: str) -> bool:
last = None
while last != len(S):
last = len(S)
S = S.replace("abc", "")
return not S

解法二(栈):

def isValid(self, S: str) -> bool:
stack = []
for ch in S:
if ch == "c":
if len(stack) < 2 or stack.pop() != "b" or stack.pop() != "a":
return False
else:
stack.append(ch)
return not stack



举报

相关推荐

0 条评论