题目:
给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
提示:
1 <= S.length <= 20000
S 仅由小写英文字母组成。
题目的理解:
删除相邻且相同的两个字符。
循环判断并删除,然后返回。
python实现
class Solution:
def removeDuplicates(self, S: str) -> str:
index = 0
string_list = list(S)
while index + 1 < len(string_list):
if string_list[index] == string_list[index + 1]:
string_list.pop(index)
string_list.pop(index)
index = index - 1
if index < 0:
index = 0
else:
index += 1
return ''.join(string_list)
提交

成就有点差啊,感觉思路很直接啊
// END 如果人没有想法,那么和门前的树有什么区别。
网友评论