/** * @param {string}S * @return {string} */ var compressString = function (S) { if (!S) return""; const stack = [[S[0], 0]]; for (const arr of S) { if (stack[stack.length - 1][0] === arr) stack[stack.length - 1][1]++; else stack.push([arr, 1]); } const res = stack.map(([a, b]) => a + b).join(""); return res.length >= S.length ? S : res; };
优化空间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * @param {string}S * @return {string} */ var compressString = function (S) { if (!S) return""; let temp = [S[0], 0]; let res = ""; for (const arr of S) { if (temp[0] === arr) temp[1]++; else { res += temp[0] + temp[1]; temp = [arr, 1]; } } res += temp[0] + temp[1]; return res.length >= S.length ? S : res; };