当前位置:网站首页>LeetCode - 1047. Remove all adjacent duplicates in a string

LeetCode - 1047. Remove all adjacent duplicates in a string

2022-08-06 07:54:34Peas Erguotou

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

题目

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

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

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

思路

In fact, it can be regarded as a stack,如果栈顶,the same as the top,Then pop the top and next top of the stack,last on the stack,In fact, it is all the characters of the final result.

代码

class Solution {
    
    public String removeDuplicates(String s) {
    
        // s 仅由小写字母组成
        char[] word = s.toCharArray();
        int length = s.length();
        int top = -1;
        for (int i = 0; i < length; ++i)
        {
    
            if (top==-1 || word[top]!=word[i])
            {
    
                word[++top]=word[i];
            }
            else
                top--;
        }
        return String.valueOf(word,0,top+1);
    }
}

结果

在这里插入图片描述
A more ingenious process of using the stack to solve problems,Use a top-of-stack pointer,如果,The character at the current position is not the same as the top of the stack pointer,Then copy the character at the current position to the next position of the top of the stack pointer.
If the character at the current position is the same as the top of the stack pointer,Then skip these two characters,把topThe pointer moves down one position to the left.and rematchtopand the case of the character at the next position.

原网站

版权声明
本文为[Peas Erguotou]所创,转载请带上原文链接,感谢
https://chowdera.com/2022/218/202208060745383280.html

随机推荐