String Compression
EasyTwo Pointers · Adobe
You are given a list of single-character strings chars. Compress it using run-length encoding and return the compressed list.
Scan chars from left to right and split it into runs of consecutive equal characters. For each run, in order:
- append the character once,
- if the run is longer than 1, append its length written as decimal digits, one digit per list entry (a run of 12 adds
"1","2").
A run of length 1 gets no count. Characters are compared exactly, so "a" and "A" are different. The same character can start a new run later if something else separates it.
Example 1
- Input:
- chars = ["x","x","x","y","z","z"]
- Output:
- ["x","3","y","z","2"]
- Explanation
- The run
xxxbecomesx,3; the singleystays as justy;zzbecomesz,2.
Example 2
- Input:
- chars = ["p","q"]
- Output:
- ["p","q"]
- Explanation
- Both runs have length 1, so no counts are written and the output matches the input.
Example 3
- Input:
- chars = ["#","#","#","#","#","#","#","#","#","#","#","#","#","k","k"]
- Output:
- ["#","1","3","k","2"]
- Explanation
- The run of 13
#characters is written as#followed by the two digit entries"1"and"3". Thenkkbecomesk,2.
Constraints
1 <= chars.length <= 2000- Each
chars[i]is a single character: an English letter, a digit, or a symbol