[Leetcode] 1047. Remove all adjacent duplicates in a string (remove-all-adjacent-duplicates-in-string) (simulation) [simple]

link

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

time consuming

Problem solving: 38 min
Problem solving: 10 min

Title

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.

Ideas

Similar to the elimination of music, two identical characters will be eliminated when they meet, and after one elimination, it may cause a chain to eliminate successively.

Record the position of the left and right neighbors of each character in the string, traverse the string, and update the positions of the left and right neighbors of the remaining characters after a series of eliminations are completed. And when the first remaining element is cut off, the position of the first remaining element is updated and recorded. After the traversal ends, the result string is added from the position of the first remaining element, and the next character added is the right neighbor character of the current character.

Time complexity: O (n) O(n)O ( n )

AC code

class Solution {
    
    
public:
    string removeDuplicates(string S) {
    
    
        int n = S.size();
        vector<pair<int, int>> slr(n);
        for(int i = 0; i < n; ++i) {
    
    
            slr[i].first = i-1;
            slr[i].second = i+1;
        }
        
        int startpos = 0;
        for(int i = 0; i < n; ++i) {
    
    
            if(S[i] == S[i+1]) {
    
    
                int l = i;
                int r = i+1;
                while((l >= 0 && r < n) && S[l] == S[r]) {
    
    
                    l = slr[l].first;
                    r = slr[r].second;
                }
                if(l >= 0) slr[l].second = r;
                else startpos = r;
                if(r < n) slr[r].first = l;
                i = r-1;
            }
        }

        string ans = "";
        for(int i = startpos; i < n; i = slr[i].second) {
    
    
            ans += S[i];
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/Krone_/article/details/114575204