Examples are
let string1 = "AAAAA"
Output: 4A1A
My output: 4A
let string2 = "AAAAAAAAABBBBBCCCCDD"
output : 4A4A1A4B1B4C2D
My output: 4A4A4B2B4C2D
If the length of a particular character is greater than 4, start counting from 1 again.
I am unable to print the one remaining character every time. Please refer to the above example:
And here is my code. Please try to improve my code and not give a new solution as much as possible.
function stringCompress(str) {
let sum = 0;
let res = ""
let demo = []
for(let i = 0; i < str.length;i++){
demo.push(i+"=" +str.substring(i,i+1))
if(str.substring(i,i+1) != str.substring(i+1,i+2) || sum == 4 ){
sum = sum+1
let temp = 0;
if(sum > 4){
sum = 4
temp = 1
}
res += sum+str.substring(i,i+1);
if(temp == 1){
sum = temp
}else{
sum = 0;
}
}
else{
sum = sum +1
}
}
return res
}
let d = "AAAAAAAAABBBBBCCCCDD"
console.log(stringCompress(d))
question from:
https://stackoverflow.com/questions/66048091/string-compression-with-a-particular-case 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…