Write a program that compresses a character string by inputting a character string consisting of uppercase letters and writing the number of repetitions to the right of the repeated character when the same character is repeated continuously. <br/ >However, if the number of repetitions is 1, it is omitted.
A string is given on the first line. The length of the string does not exceed 100.
KKHSSSSSSSE
Prints a compressed string on the first line.
K2HS7E
Object.entries()
function solution(s) {
let answer = '';
let cnt = 0;
let temp = '';
for (let [i, x] of Object.entries(s)) {
if (!temp) temp = x;
if (temp === x) cnt++;
else {
answer += temp;
if (cnt > 1) answer += cnt;
temp = x;
cnt = 1;
}
if (parseInt(i) === s.length - 1) answer += x;
}
return answer;
}
function solution(s) {
let answer = '';
let cnt = 1;
s = s + ' ';
for (let i = 0; i < s.length - 1; i++) {
if (s[i] === s[i + 1]) cnt++;
else {
answer += s[i];
if (cnt > 1) answer += String(cnt);
cnt = 1;
}
}
return answer;
}