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:
'a' at indices i = 0 and i = 3 are close as 3 - 0 = 3 <= k.'a' and s = "abc".Example 2:
Input: s = "aabca", k = 2
Output: "abca"
Explanation:
'a' at indices i = 0 and i = 1 are close as 1 - 0 = 1 <= k.'a' and s = "abca".'a' characters at indices i = 0 and i = 3 are not close as k < 3, so no further merges occur.Example 3:
Input: s = "yybyzybz", k = 2
Output: "ybzybz"
Explanation:
'y' at indices i = 0 and i = 1 are close as 1 - 0 = 1 <= k.'y' and s = "ybyzybz".'y' at indices i = 0 and i = 2 are close as 2 - 0 = 2 <= k.'y' and s = "ybzybz".
Constraints:
1 <= s.length <= 1001 <= k <= s.lengths consists of lowercase English letters.Solutions for this problem are being prepared.
Try solving it yourselfPractice Merge Close Characters with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor