[LeetCode] 1047. Remove All Adjacent Duplicates In String 移除字符串中所有相鄰的重復字符



Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.

We repeatedly make duplicate removals on S until we no longer can.

Return the final string after all such duplicate removals have been made.  It is guaranteed the answer is unique.

Example 1:

Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Note:

  1. 1 <= S.length <= 20000
  2. S consists only of English lowercase letters.

這道題給了一個字符串,讓移除所有相鄰的重復字符,注意之前不相鄰的字符可以在其他字符移除后變的相鄰,從而形成的新的相鄰的重復字符,所以只是簡單移除一次不能保證能得到最終的結果。這里需要借助棧的思路來做,可以用字符串來模擬棧的后入先出的特性。遍歷每個字符,若 res 不空,且最后一個字符和當前字符相同,則移除掉 res 的最后一個字符,否則將當前字符加入 res 中,這樣最后剩下的即為所求,參見代碼如下:


解法一:

class Solution {
public:
    string removeDuplicates(string S) {
        string res;
        for (char c : S) {
            if (!res.empty() && res.back() == c) {
                res.pop_back();
            } else {
                res.push_back(c);
            }
        }
        return res;
    }
};

我們也可以使用雙指針來做,兩個指針i和j,其中i指向去除重復后的最后一個字符的位置,j為遍歷字符串S的位置,首先將 S[j] 賦值給 S[i],然后看若i大於0,且 S[i-1] 和 S[i] 相等的,i自減2,這樣就移除了重復,最后根據i的位置取出子串返回即可,參見代碼如下:


解法二:

class Solution {
public:
    string removeDuplicates(string S) {
        int n = S.size(), i = 0;
        for (int j = 0; j < n; ++j, ++i) {
            S[i] = S[j];
            if (i > 0 && S[i - 1] == S[i]) i -= 2;
        }
        return S.substr(0, i);
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1047


類似題目:

Remove All Adjacent Duplicates in String II


參考資料:

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/294893/JavaC%2B%2BPython-Two-Pointers-and-Stack-Solution

https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/discuss/294964/JavaPython-3-three-easy-iterative-codes-w-brief-explanation-analysis-and-follow-up.


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM