LeetCode1047. 刪除字符串中的所有相鄰重複項

1047. Remove All Adjacent Duplicates In String

[Easy] 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.

題目:給出由小寫字母組成的字符串 S重複項刪除操作會選擇兩個相鄰且相同的字母,並刪除它們。在 S 上反覆執行重複項刪除操作,直到無法繼續刪除。在完成所有重複項刪除操作後返回最終的字符串。答案保證唯一。

思路:棧。因爲題目只要求判斷相鄰的兩個字母,所以當前的字符和棧頂字符相同的時候,則刪除棧頂元素。

工程代碼下載 GitHub

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

思路2:雙指針,以下轉自lee215i表示輸出字符串中待設置下一個字符的位置,j表示輸入字符串的當前循環位置。

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

You can easily update this solution to remove more duplicates.
Now it’s a specil case where we only remove replicates k = 2.

1209. Remove All Adjacent Duplicates in String II

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章