Leetcode - String Compression
https://leetcode.com/problems/string-compression/
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
Follow up:
Could you solve it using only O(1) extra space?
Example 1:
Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | func compress(chars []byte) int { if len(chars) < 2 { return len(chars) } result := 0 left := 0 right := left+1 for right < len(chars) { right = left+1 for right < len(chars) && chars[right] == chars[left] { right++ } if right == len(chars) { break } //fmt.Println("right - left: ", right - left) chars[result] = chars[left] if right - left == 1 { left = right result++ continue } if left + 1 < len(chars) { count := getCounts(right - left) for i := 1; i < len(count)+1; i++ { chars[result+i] = count[i-1] } result += 1 + len(count) left = right } } chars[result] = chars[left] if right - left == 1 { result++ } else { count := getCounts(right - left) for i := 1; i < len(count)+1; i++ { chars[result+i] = count[i-1] } result += 1 + len(count) } return result } func getCounts(num int ) []byte { result := []byte{} for num > 0 { result = append(result, byte(num%10+ '0' )) num /= 10 } for i := 0; i < len(result)/2; i++ { result[i], result[len(result)-i-1] = result[len(result)-i-1], result[i] } return result } |