以下为ChatGPT自动生成的解答,正确与否请自行判断。 也许你也可以从大家的发帖中找到想要的答案!
BFE.devAI解答 - JavaScript 代码题
97. 压缩字符串
function compress(str) { let compressed = ''; let count = 1; for (let i = 0; i < str.length; i++) { if (str[i] === str[i+1]) { // 当前字符和下一个字符相同,计数增加 count++; } else { if (count > 1) { // 当前字符计数大于1, 添加计数到压缩字符串中 compressed += count; } compressed += str[i]; // 添加当前字符到压缩字符串中 count = 1; // 重置计数 } } return compressed;}
测试结果:
compress("a"); // "a"
compress("aa"); // "a2"
compress("aaa"); // "a3"
compress("aaab"); // "a3b"
compress("aaabb"); // "a3b2"
compress("aaabba"); // "a3b2a"