Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 1047. Remove All Adjacent Duplicates In String

Rain Hu

1047. Remove All Adjacent Duplicates In String


一、題目

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. Stack

string removeDuplicates(string s) {
    string res = "";
    for (char c : s) {
        if (res.empty()) {
            res.push_back(c);
        } else {
            if (res.back() == c) {
                res.pop_back(); 
            } else {
                res.push_back(c);
            }
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 21. Merge Two Sorted Lists
Next
[LeetCode] 901. Online Stock Span