LeetCode-in-Java

3853. Merge Close Characters

Medium

You are given a string s consisting of lowercase English letters and an integer k.

Two equal characters in the current string s are considered close if the distance between their indices is at most k.

When two characters are close, the right one merges into the left. Merges happen one at a time, and after each merge, the string updates until no more merges are possible.

Return the resulting string after performing all possible merges.

Note: If multiple merges are possible, always merge the pair with the smallest left index. If multiple pairs share the smallest left index, choose the pair with the smallest right index.

Example 1:

Input: s = “abca”, k = 3

Output: “abc”

Explanation:

Example 2:

Input: s = “aabca”, k = 2

Output: “abca”

Explanation:

Example 3:

Input: s = “yybyzybz”, k = 2

Output: “ybzybz”

Explanation:

Constraints:

Solution

public class Solution {
    public String mergeCharacters(String s, int k) {
        StringBuilder result = new StringBuilder();
        result.ensureCapacity(s.length());
        int[] cnt = new int[26];
        for (int t = 0; t < s.length(); t++) {
            char c = s.charAt(t);
            int idx = c - 'a';
            if (cnt[idx] > 0) {
                continue;
            }
            result.append(c);
            cnt[idx]++;
            if (result.length() > k) {
                char drop = result.charAt(result.length() - k - 1);
                cnt[drop - 'a']--;
            }
        }
        return result.toString();
    }
}