需要一些简单的解决方案,在js中使用短代码进行字符串压缩

问题描述 投票:0回答:1

这里我创建了一个用于字符串压缩的程序,因此对于输入 chars = ["a","a","b","b","c","c","c"] 我们得到的输出如下6 个字符 [“a”、“2”、“b”、“2”、“c”、“3”]。所以我使用数组方法创建了一个程序,该程序也非常冗长且复杂。有没有使用两指针或递归方法以很少的代码和效率来解决该程序的解决方案?您能提供非常短的代码吗?代码如下。

var compress = function(chars) {
 if (!chars.length) {
    return 0;
  }
   let j = 0;                 
  let cur = chars[0];        
  let counter = 0;         
   for (let i = 0; i <= chars.length; i++) {
  
    if (chars[i] === cur) {
      counter++;              
    } else {
      // Otherwise, add the current character and count to the compressed array
      chars[j] = cur;        
      if (counter > 1) {
        const s = counter.toString();
        for (let k = 0; k < s.length; k++) {
          chars[++j] = s[k];  
        }
      }
      j++;                  
      cur = chars[i];      
      counter = 1;           
    }
   }
   return j
};
console.log(compress ('aaaabbc'))//a4b2c
javascript string data-structures logic
1个回答
0
投票

可以使用两指针的方式来实现字符串压缩,代码更加简洁。这是您的程序的较短版本:

var compress = function(chars) {
  let i = 0;
  let count = 1;
  
  for (let j = 1; j <= chars.length; j++) {
    if (j < chars.length && chars[j] === chars[j - 1]) {
      count++;
    } else {
      chars[i++] = chars[j - 1];

      if (count > 1) {
        for (let digit of count.toString()) {
          chars[i++] = digit;
        }
      }

      count = 1;
    }
  }

  return i;
};

console.log(compress(['a', 'a', 'b', 'b', 'c', 'c', 'c']));
console.log(compress('aaaabbc')); 
© www.soinside.com 2019 - 2024. All rights reserved.