LeetCode1047. Remove all adjacent duplicates in a string

Source: LeetCode
Link: https://leetcode-cn.com/problems/remove-all-adjacent-duplicates-in-string
Difficulty: 简单
Title description

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".

prompt:

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

Violent solution:

class Solution {
    
    
public:
    string removeDuplicates(string S) {
    
    
        int n=S.length();
        if(n<2){
    
    
            return S;
        }
        string::iterator it;
        for(int i=0;i<S.length()-1;){
    
    
            if(S.length()<2){
    
    
                return S;
            }
            if(S[i]==S[i+1]){
    
    
                S.erase(i,2);
                i=0;
            }else{
    
    
                i++;
            }
        }
        return S;
    }
};

Stack:

class Solution {
    
    
public:
    string removeDuplicates(string S) {
    
    
        int n=S.length();
        if(n<2){
    
    
            return S;
        }
        string ans;
        for(int i=0;i<S.length();i++){
    
    
            if(ans.back()!=S[i]||ans.empty()){
    
    
                ans.push_back(S[i]);
            }else{
    
    
                ans.pop_back();
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/chaokudeztt/article/details/114579796