Remove all adjacent duplicates in the string
Given a string of lowercase letters S
, the duplicate deletion operation will select two adjacent and identical letters and delete them.
In S
the implementation of the repeated duplicate deletion, we can not continue until deleted.
Return the final string after completing all deduplication operations. The answer is guaranteed to be unique.
Examples
输入:"abbaca"
输出:"ca"
解释:
例如,在 "abbaca" 中,我们可以删除 "bb" 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 "aaca",其中又只有 "aa" 可以执行重复项删除操作,所以最后的字符串为 "ca"。
prompt
1 <= S.length <= 20000
S
It consists only of lowercase English letters.
Problem-solving ideas
The processing method for the Nth (N> 1) character:
- If S [N] == S [N + 1]
- S [N] and S [N + 1] are duplicates and need to be cleared
- Determine whether S [N + 2] is equal to S [N-1]. If they are equal, the duplicates continue to be cleared; if they are not equal, continue to make the best judgment from the N + 2th character string
- If S [N]! = S [N + 1]
- Continue to judge from the N + 1th character
Need to make a good judgment on whether N + 2 and N-1 cross the boundary
Solution JAVA implementation
Click to view other problem solving methods
public String removeDuplicates(String S) {
if (S.length() <= 0) {
return "";
}
Deque deque = new ArrayDeque<>();
char[] charArray = S.toCharArray();
deque.addLast(charArray[0]);
for (int i = 1; i < charArray.length; i++) {
if (!deque.isEmpty() && deque.peekLast().equals(charArray[i])) {
deque.pollLast();
continue;
} else {
deque.addLast(charArray[i]);
}
}
StringBuilder result = new StringBuilder();
while (!deque.isEmpty()) {
result.append(deque.pollFirst());
}
return result.toString();
}