字符串javascript访谈q

时间:2018-03-07 01:05:52

标签: javascript string algorithm

我有字符串面试问题,我的解决方案是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');
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

您可以改进此方法的一种方法是不执行拆分。字符串也是可索引的:

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("");
};

答案 1 :(得分:1)

将此方法与正则表达式一起使用: transactions

正则表达式解释: Regex to match/group repeating characters in a string

/((.)\2*)/g

.as-console-wrapper { max-height: 100% !important; top: 0; }
networkRestrictions:
  Type: AWS::IAM::ManagedPolicy
  Properties:
    PolicyDocument:
      Version: 2012-10-17
      Statement:
        # NOTE: Code Commit accesses KMS as your user using a fake ip
        # address of `codecommit.amazonaws.com`. This value isn't a valid
        # so IAM policy validation won't allow it in the SourceIp conditions
        # It also provides no other fields that we can match on to limit
        # KMS operations to the codecommit service.
        #
        # https://docs.aws.amazon.com/codecommit/latest/userguide/encryption.html
        # https://stackoverflow.com/questions/48873309/aws-code-comitter-encryptionkeyaccessdeniedexception-errors-after-ip-restriction#
        #
        - Effect: Deny
          NotAction:
            - kms:Decrypt
            - kms:Encrypt
            - kms:Decrypt
            - kms:ReEncrypt
            - kms:GenerateDataKey
            - kms:GenerateDataKeyWithoutPlaintext
            - kms:DescribeKey
          Resource: "*"
          Condition:
            NotIpAddress:
              aws:SourceIp:
                - "10.1.2.0/24"

答案 2 :(得分:1)

您希望实现的目标是run-length encoding

这个问题有很多existing Javascript implementations