String Compression
Given an array of characters chars, compress it using following algorithm:
Begin with an empty string s. For each group of consecutive repeating characters in chars:
- If the group length is $1$, append the character to s.
- Otherwise, append the charactoer followed by the group’s length.
The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are $10$ or longer will be split into multiple characters in chars.
After modifying the input array, return the new length of the array.
Example:
1 | Input: chars = ["a","a","b","b","c","c","c"]; |
1 | Input: chars = ["a"]; |
1 | Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]; |
Constraints:
- $ 1 \le l_{chars} \le 2000 $
- $chars_i$ is a lower case English letter, uppercase English letter, digit, or symbol.
Solution
1 | class Solution { |
Explanation:
Using two pointers to iterate original string and trach generated new string. Here, use i to iterate whole string and count the length of each group. Once a group’s length is detected, use another pointer ans to write on the original string.
1 | "aabbccc" |