# LeetCode - 1047. Remove all adjacent duplicates in a string

2022-08-06 07:54:34

# 思路

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.

https://chowdera.com/2022/218/202208060745383280.html