当前位置:网站首页>Leetcode 1209. Delete all adjacent duplicates II in the string

Leetcode 1209. Delete all adjacent duplicates II in the string

2022-06-23 11:47:00 I'm not xiaohaiwa~~~~

 Insert picture description here
Give you a string s,「k Double duplicate deletion 」 Will be from s Choose from k Two adjacent and equal letters , And delete them , Connect the left and right sides of the deleted string .

You need to s Repeat the deletion operation for an unlimited number of times , Until it can't continue .

After performing all deletion operations , Returns the resulting string .

The answer to this question is guaranteed to be unique .

Example 1:

 Input :s = "abcd", k = 2
 Output :"abcd"
 explain : There is nothing to delete .

Example 2:

 Input :s = "deeedbbcccbdaa", k = 3
 Output :"aa"
 explain : 
 Delete first  "eee"  and  "ccc", obtain  "ddbbbdaa"
 And then delete  "bbb", obtain  "dddaa"
 Finally delete  "ddd", obtain  "aa"

Example 3:

 Input :s = "pbbcggttciiippooaais", k = 2
 Output :"ps"
 

Tips :

  • 1 <= s.length <= 10^5
  • 2 <= k <= 10^4
  • s There are only lowercase letters in .

Code:

class Solution {
    
public:
    string removeDuplicates(string s, int k) {
    
        
        string res;
        
        int size=s.length();
        int num=0;
        for(int i=0;i<size;i++)
        {
    
            
            if(res.back()!=s[i])
            {
    
                
                res.push_back(s[i]);
                num=1;
                continue;
            }
            else
            {
    
                num++;
                res.push_back(s[i]);
                if(num==k)
                {
    
                    for(int j=0;j<k;j++)
                    {
    
                        res.pop_back();
                    }
                    num=1;
                    for(int j=res.size()-1;j>=0;j--)
                    {
    
                        if((j-1)>=0)
                        {
    
                            if(res[j]==res[j-1])
                                num++;
                            else
                                break;
                        }
                    }   
                }
            }
        }
        return res;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231130449051.html