Alternating Character Compression
Given a string s and an integer k, implement a function that compresses consecutive identical characters. A sequence of identical characters will be compressed only if its length is k or greater. The compression should transform N identical characters C (where N >= k) into C followed by N (e.g., "AAAA" with k=3 becomes "A4"). If a sequence of identical characters has a length less than k, it should remain uncompressed. The final output string should be the result of applying this compression throughout the input string.
[ "AAABBCDDDDEEEF", "3" ]
Explanation. For s="AAABBCDDDDEEEF" and k=3:"AAA" (count 3) becomes "A3"."BB" (count 2) remains "BB" as 2 < 3."DDDD" (count 4) becomes "D4"."EEE" (count 3) becomes "E3"."F" (count 1) remains "F" as 1 < 3.Result: A3BBD4E3F.
[ "A", "1" ]
Explanation. For s="A" and k=1:"A" (count 1) becomes "A1" as 1 >= 1.Result: A1.
[ "AAAAAAAAAA", "5" ]
Explanation. For s="AAAAAAAAAA" and k=5:"AAAAAAAAAA" (count 10) becomes "A10" as 10 >= 5.Result: A10.
[ "ABCDE", "2" ]
Explanation. For s="ABCDE" and k=2:Each character appears once, which is less than 2. Thus, no compression occurs.Result: ABCDE.
[ "XXYYYZZZZ", "3" ]
Explanation. For s="XXYYYZZZZ" and k=3:"XX" (count 2) remains "XX" as 2 < 3."YYY" (count 3) becomes "Y3"."ZZZZ" (count 4) becomes "Z4".Result: XXY3Z4.
[ "HHHHHHHHHHH", "11" ]
Explanation. For s="HHHHHHHHHHH" and k=11:"HHHHHHHHHHH" (count 11) becomes "H11" as 11 >= 11.Result: H11.
[ "MMMMNNNOPPPP", "4" ]
Explanation. For s="MMMMNNNOPPPP" and k=4:"MMMM" (count 4) becomes "M4"."NNN" (count 3) remains "NNN" as 3 < 4."O" (count 1) remains "O" as 1 < 4."PPPP" (count 4) becomes "P4".Result: M4NNNOP4.
Follow-up: What if the compression format needed to include a delimiter, e.g., 'C(N)' instead of 'CN'?
- `1 <= s.length <= 10^5`- `1 <= k <= s.length`- `s` consists of uppercase English letters.
- Views
- 4