Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

删除字符串中的所有相邻重复项 #241

Open
louzhedong opened this issue Apr 20, 2021 · 0 comments
Open

删除字符串中的所有相邻重复项 #241

louzhedong opened this issue Apr 20, 2021 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

给出由小写字母组成的字符串 S,重复项删除操作会选择两个相邻且相同的字母,并删除它们。

在 S 上反复执行重复项删除操作,直到无法继续删除。

在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。

示例:

输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。

提示:

1 <= S.length <= 20000
S 仅由小写英文字母组成。

思路

用一个栈来保存字符串的项,当当前项和栈顶的项相同时,即为两个连续的字符

解答

var removeDuplicates = function(S) {
    var stack = [], i = 1, length = S.length;
    stack.push(S[0]);
    for (;i < length; i++) {
        if (stack[stack.length - 1] == S[i]) {
            stack.pop();
        } else {
            stack.push(S[i]);
        }
    }

    return stack.join('');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant