1047. Remove all adjacent duplicates in a string (Remove All Adjacent Duplicates In String) | LeetCode Question 1047

Remove all adjacent duplicates in the string

Click to enter LeetCode

Given a string of lowercase letters S, the duplicate deletion operation will select two adjacent and identical letters and delete them.
In Sthe 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. 1 <= S.length <= 20000
  2. 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]
    1. S [N] and S [N + 1] are duplicates and need to be cleared
    2. 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();
}
Published 7 original articles · won 3 · views 315

Guess you like

Origin blog.csdn.net/sl285720967/article/details/103135063