443. Compressed string
// js
JSON. parse() method
JSON.stringify() method
// java
int[][] ghosts = JSON.parseObject(cin.nextLine(), int[][].class);
// go
if errJson2 := json.Unmarshal([]byte(targetInput), &target); errJson2 != nil {
println(“errJson2:”, errJson2)
return
}
// python
json.loads() method
json.json() method
Gives you a character array chars, please use the following algorithm for compression:
Start with an empty string s. For each group of consecutively repeated characters in chars:
If the group has length 1, append the characters to s.
Otherwise, characters need to be appended to s, followed by the length of the group.
The compressed string s should not be returned directly, but needs to be dumped into the character array chars. It should be noted that if the group length is 10 or more, it will be split into multiple characters in the chars array.
After modifying the input array, please return the new length of the array.
You must design and implement an algorithm that uses only constant extra space to solve this problem.
Example 1:
Input: chars = [“a”,”a”,”b”,”b”,”c”,” c”,”c”]
Output: Return 6, 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”.
Example 2:
Input: chars = [“a”]
Output: Return 1, the first character of the input array should be: [“a”]
Explanation:
No string was replaced.
Example 3:
Input: chars = [“a”,”b”,”b”,”b”,”b”,”b”,”b”,”b” ,”b”,”b”,”b”,”b”,”b”]
Output: Return 4, the first 4 characters of the input array should be: [“a”,”b”,” 1″,”2″].
Explanation:
Since the character “a” is not repeated, it will not be compressed. “bbbbbbbbbbbb” is replaced by “b12”.
Note that each number has its own position in the array.
package main
import (
“encoding/json”
“fmt”
)
func compress(chars []byte) int {
write, left := 0, 0
for read, ch := range chars {
if read == len(chars)-1 || ch != chars[read+1] {
chars[write] = ch
write++
num := read – left + 1
if num > 1 {
anchor := write
for ; num > 0; num /= 10 {
chars[write] = ‘0’ + byte(num%10)
write++
}
s := chars[anchor:write]
for i, n := 0, len(s); i <n/2; i++ {
s[i], s[n-1-i] = s[n-1-i], s[i]
}
}
left = read + 1
}
}
return write
}
func main() {
var charsInput string
if _, err := fmt.Scanf(“%s\n”, &charsInput) ; err != nil {
println(“err:”, err)
return
}
var chars []byte
if errJson2 := json.Unmarshal([]byte(charsInput ), &chars); errJson2 != nil {
println(“errJson2:”, errJson2)
return
}
println(compress(chars))
}
View Code