1047. deletes all adjacent duplicate entries in a string

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

String S is given by the lowercase letters, delete duplicates and selects two identical letters adjacent to, and remove them.

Performed on the S repeatedly duplicates deletion, can not continue until deleted.

Returns the final string after the completion of all duplicates deletion. The only answer guarantee.

 

Example:

Enter: "abbaca"
Output: "ca"
interpretation:
for example, in "abbaca", we can remove the "bb" as the two adjacent letters and the same, this is the only duplicates this time can perform delete operations. After we get the string "aaca", which has only "aa" can perform delete duplicates, so the final string is "ca".
 

prompt:

. 1 <= s.length <= 20000
S only by the lower case letters.

A, with a stack, because the last-out stack has characteristics, so the reverse is determined.

class Solution {
public:
    string removeDuplicates(string S) {
        int len = S.size();
        stack<char> ans;
        string temp = "";

        ans.push(S[len - 1]);
        for(int i = (len - 2); i >= 0; i--)
        {
            // 注意栈为空时直接把字符压入栈即可
            if(!ans.empty() && S[i] == ans.top())
            {
                ans.pop();
            }
            else
            {
                ans.push(S[i]);
            }
        }

        while(!ans.empty())
        {
            temp += ans.top();
            ans.pop();
        }

        return temp;
    }
};

Second, a direct by-added character string, and determines whether the end of the string is repeated, the usage of several strings learned functions

class Solution {
public:
    string removeDuplicates(string S) {
       string ans = "";
       int len = S.size();

       ans.push_back(S[0]);
       for(int i = 1; i < len; i++)
       {
            // 注意字符串为空时直接把字符加入字符串末尾中即可
           if((ans.size() != 0) && S[i] == ans.back()) ans.pop_back();
           else ans.push_back(S[i]); 
       }

       return ans;
    }
};

 

Published 58 original articles · won praise 6 · views 7032

Guess you like

Origin blog.csdn.net/weixin_43569916/article/details/104096085