1209. Remove All Adjacent Duplicates in String II - kumaeki/LeetCode GitHub Wiki

Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made.

It is guaranteed that the answer is unique.

Example 1:

Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.

Example 2:

Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: 
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"

Example 3:

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

Constraints:

  • 1 <= s.length <= 10^5
  • 2 <= k <= 10^4
  • s only contains lower case English letters.

解法1

最简单的, 就是遍历,找到可以去掉的就先去掉, 然后把新字符串再从头开始找,循环往复,直到找不到可以去掉的为止.

class Solution {
    public String removeDuplicates(String s, int k) {
        int cnt = 1;
        char last = s.charAt(0);
        for(int i=1;i<s.length();i++){
            char cur = s.charAt(i);
            if(cur==last){
                cnt++;
            }else{
                cnt = 1;
                last = cur;
            }
            
            if(cnt == k)
                return removeDuplicates(s.substring(0,i-k+1)+s.substring(i+1),k);
        }
        return s;
    }
}

解法2

用两个stack,一个储存字符,一个储存字符的个数.

class Solution {
    public String removeDuplicates(String s, int k) {
        ArrayDeque<Character> que = new ArrayDeque<Character>();
        ArrayDeque<Integer> queCount = new ArrayDeque<Integer>();
        for(char c : s.toCharArray()){
            // 如果不存在相邻且相同的字符,压入字符,并重新计数
            if(que.isEmpty() || c != que.getLast()){
                que.addLast(c);
                queCount.addLast(1);
            }
            // 如果存在相邻且相同的字符
            else{
                // 如果字符个数等于k
                if( k - 1 == queCount.getLast().intValue()){
                    int count = queCount.removeLast();
                    while(count-- > 0){
                        que.removeLast();
                    }
                    
                }
                // 如果字符个数小于k
                else{
                    queCount.addLast(queCount.removeLast() + 1);
                    que.addLast(c);
                }
            }
        }
        if(que.isEmpty())
            return "";
        
        char[] charArr = new char[que.size()];
        for(int i = 0; i < charArr.length; i++){
            charArr[i] = que.removeFirst();
        }
        return new String(charArr);
        
    }
}
⚠️ **GitHub.com Fallback** ⚠️