LeetCode Brush Question 1047. Delete all adjacent duplicates in the string

LeetCode Brush Question 1047. Delete all adjacent duplicates in the string

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Topic :
    Given a string S consisting of lowercase letters, the duplicate deletion operation will select two adjacent and identical letters and delete them. Repeat the deduplication operation on S until it can no longer be deleted. The final string is returned after all the deduplication operations are completed. The answer is guaranteed to be unique.
  • Example :
示例 1 :
输入:"abbaca"
输出:"ca"
解释:例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
  • Tips :
    1. 1 <= S.length <= 20000
    2. S 仅由小写英文字母组成。
  • Code 1:
class Solution:
    def removeDuplicates(self, S: str) -> str:
        a = []
        for i in range(len(S)):
            if a == [] or a[-1] != S[i]:
                a.append(S[i])
                continue
            elif a[-1] == S[i]:
                a.pop()
                continue
        return(''.join(a))
# 执行用时 :156 ms, 在所有 Python3 提交中击败了33.75%的用户
# 内存消耗 :13.9 MB, 在所有 Python3 提交中击败了100.00%的用户
  • Algorithm description:
    create an empty stack a, store Sthe elements, if Sthe current element and athe top element of the stack are equal, delete the top element a[-1]; if Sthe current element and athe top element of the stack are not equal or aempty, Sthe current element Add to the amiddle, until Sall the elements in the amiddle are traversed , and the middle elements are output in string format!

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/106708134