[Stack] [leetcode] [Simple] 1047. Delete all adjacent duplicates in the string

topic:

Given a string S consisting of lowercase letters, the duplicate deletion operation will select two adjacent and identical letters and delete them.

Repeat the deduplication operation on S until it can no longer be deleted.

The final string is returned after all the deduplication operations are completed. The answer is guaranteed to be unique.

Example:

Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca", we can delete "bb". Since the two letters are adjacent and the same, this is the only duplicate item that can be deleted at this time. Then we get the string "aaca", of which only "aa" can perform the deduplication operation, so the final string is "ca".

Original title address:

1047. Remove all adjacent duplicates in a string

Problem-solving ideas:

Analyzing the example found that a new adjacent letter aa appears after deleting bb, and it needs to be deleted continuously. This is similar to the problem of matching parentheses, so the stack is adopted.

Traverse the entire string, and when the stack is empty or the top element of the stack is different from the current character, push it to the stack; otherwise, it pops the stack (popping represents deletion). The remaining characters in the last stack are the answer.

class Solution {
public:
    string removeDuplicates(string S) {
        string ret(S); // 把字符串当做栈
        int top = -1;  // 栈顶指针
        for (int i = 0; i < S.size(); i++) {
            if (top < 0 || S[i] != ret[top]) {
                ret[++top] = S[i]; // 入栈
            } else {
                top--; // 出栈
            }
        }
        ret.resize(top + 1); // 移除后面字符
        return ret;
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/114578593