描述
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Note:
- 1 <= S.length <= 20000
- S consists only of English lowercase letters.
解析
根据题意,可以利用栈数据结构,从第二个字符开始遍历 S ,只要 res 不为空,且字符和 res 中最后一个字符相同, 就去掉 res 的最后一个字符 ,否则就追加到 res 中,遍历结束即可得到答案。
解答
class Solution(object):
def removeDuplicates(self, S):
"""
:type S: str
:rtype: str
"""
res = [S[0]]
for c in S[1:]:
if len(res) and c == res[-1]:
res.pop()
else:
res.append(c)
return "".join(res)
运行结果
Runtime: 72 ms, faster than 56.66% of Python online submissions for Remove All Adjacent Duplicates In String.
Memory Usage: 14 MB, less than 82.37% of Python online submissions for Remove All Adjacent Duplicates In String.
原题链接:leetcode.com/problems/re…
您的支持是我最大的动力