algorighm/leetcode/简单/删除字符串中所有重复项.js

48 lines
1.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
1047. 删除字符串中的所有相邻重复项
简单
相关标签
相关企业
提示
给出由小写字母组成的字符串 S重复项删除操作会选择两个相邻且相同的字母并删除它们。
在 S 上反复执行重复项删除操作,直到无法继续删除。
在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca"
其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
提示:
1 <= S.length <= 20000
S 仅由小写英文字母组成。
*/
/**
* @param {string} s
* @return {string}
*/
const removeDuplicates = function (s) {
// 遍历字符串把字符串push到stack里面如果当前加入的字符和末尾的字符相同就pop掉
const len = s.length;
const result = [];
for (let i = 0; i < len; i++) {
if (result.slice(-1)[0] === s.charAt(i)) {
result.pop();
} else {
result.push(s.charAt(i));
}
}
return result.join('');
};
console.log(removeDuplicates('abbaca'));