【问题标题】:improve run-length-encoding algorithm改进游程编码算法
【发布时间】:2018-08-15 00:03:28
【问题描述】:

我有一个关于运行长度编码的字符串面试问题,我的解决方案是 O(n)。有什么办法可以改善吗:

  • 输入是 AABBBCAAEE
  • 输出假设为 A2B3C1A2E2

const firstString=(str)=>{
  const arr = str.split('');
  let counter = 1;
  let result ='';
  for (let i=0; i<arr.length; i++){
    if(arr[i] === arr[i+1]){
      counter++;
    } else {
      result +=arr[i]+counter;
      counter = 1;
    }
  } return result
};
firstString('AABBBCAAEE');

【问题讨论】:

  • 你别无选择,只能查看每个字母,所以我认为你不能做得比 O(n) 更好。
  • 您是否在寻求改善大 O 时间的方法?或者您是否也对总体上改进它的方法感兴趣(比如让代码更漂亮、更简洁)?
  • 我想看看有没有办法在大 O 方面进行改进

标签: javascript string algorithm encoding run-length-encoding


【解决方案1】:

将此方法与正则表达式一起使用: Regex to match/group repeating characters in a string

正则表达式解释: /((.)\2*)/g

var str = 'AABBBCAAEE';
var result = str.replace(/((.)\2*)/g, function(match) {
  var [letter] = match;
  return `${letter}${match.length}`;
});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 你会知道这个的时间复杂度吗?还是 O(n) 吗?
  • @0x499602D2 是的,它是 O(n),因为取决于字符串的长度。这种方法在复杂性方面更出色,而不是改进。
  • 我想看看有没有办法在 Big O 方面进行改进,但看起来不可能,而且该解决方案看起来更优雅
【解决方案2】:

改善这一点的一种方法是不执行拆分。字符串也是可索引的:

let firstString = (str) => {
  if (str.length <= 0) {
    return "";
  }
  const result = [];
  result.push(str[0]);
  let counter = 1;
  for (let i = 1; i < str.length; i++) {
    if (result[result.length - 1] === str[i]) {
      counter++;
    } else {
      result.push(counter, str[i]);
      counter = 1;
    }
  }
  result.push(counter);
  return result.join("");
};

【讨论】:

    【解决方案3】:

    你想要达到的是run-length encoding

    有不少existing Javascript implementations针对这个问题。

    【讨论】:

      【解决方案4】:

      Python 实现 时间 - O(n),空间 - O(n)

      def encode(_str):
          n = len(_str)
      
          if _str == _str[0] * n:
              return f'{n}{_str[0]}'
      
          i, _count = 1, 1
          encoding = ''
      
          while i < n:
              if _str[i] == _str[i-1]:
                  _count += 1
              else:
                  encoding += f'{_count}{_str[i-1]}'
                  _count = 1
      
              i += 1
      
          encoding += f'{_count}{_str[i-1]}'  # last iteration
      
          return encoding
      
      
      assert encode('WWWWWW') == '6W'
      assert encode('WWWWWWWWWBBBBBBB') == '9W7B'
      assert encode('WWWWWWWWWBBBBBBBR') == '9W7B1R'
      assert encode('W') == '1W'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-31
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 2013-09-26
        • 1970-01-01
        相关资源
        最近更新 更多