4019. Merge Close Characters II π
Description
You are given a string s consisting of lowercase English letters and an integer k.
Two equal characters s[i] and s[j], where 0 <= i < j < s.length, are considered close if j - i <= k. All indices refer to the current string.
Repeatedly perform the following operation until no close pair remains:
- Among all close pairs
(i, j), choose the pair with the smallesti. If multiple pairs have the samei, choose the one with the smallestj. - Merge the right character into the left character by removing
s[j]froms. The characters[i]remains unchanged, and the remaining characters are reindexed.
Return the resulting string after performing all possible merges.
Β
Example 1:
Input: s = "abca", k = 3
Output: "abc"
Explanation:
- The characters
'a'at indices 0 and 3 are close because3 - 0 = 3 <= k. - Remove the right
'a', resulting ins = "abc". - No close pair remains, so no further merges are performed.
Example 2:
Input: s = "aabca", k = 2
Output: "abca"
Explanation:
- The characters
'a'at indices 0 and 1 are close because1 - 0 = 1 <= k. - Remove the right
'a', resulting ins = "abca". - The remaining
'a'characters are at indices 0 and 3. Since3 - 0 = 3 > k, no further merges are performed.
Example 3:
Input: s = "yybyzybz", k = 2
Output: "ybzybz"
Explanation:
- The characters
'y'at indices 0 and 1 are close because1 - 0 = 1 <= k. This pair has the smallest left index among all close pairs. - Remove the right
'y', resulting ins = "ybyzybz". - The characters
'y'at indices 0 and 2 are now close because2 - 0 = 2 <= k. - Remove the right
'y', resulting ins = "ybzybz". - No close pair remains, so no further merges are performed.
Β
Constraints:
1 <= s.length <= 5 * 1051 <= k <= s.lengthsconsists of lowercase English letters.
Solutions
Solution 1: Hash Table
We use a hash table \(\textit{last}\) to record the last occurrence position of each character in the answer string. We iterate over each character in \(s\) from left to right. Let \(\textit{cur}\) be the current length of the answer. If the character has appeared before and the difference between \(\textit{cur}\) and its last occurrence is at most \(k\), we skip it; otherwise, we append the character to the answer and update its position in the hash table.
Each merge always removes the right character, so the positions in the answer are exactly the indices in the current string. This greedy process is equivalent to repeatedly performing the required merge operations.
The time complexity is \(O(n)\), and the space complexity is \(O(|\Sigma|)\), where \(n\) is the length of the string, and \(|\Sigma|\) is the size of the character set. In this problem, the character set consists of lowercase English letters, so \(|\Sigma|\) is a constant.
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |