在从数组末尾循环并在适当位置添加字符时遇到重新索引数组的麻烦

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

我正在尝试解决这个特定的算法问题:

您将获得一个授权许可,表示为字符串S,仅包含字母数字字符和破折号。字符串由N个破折号分隔为N + 1个组。

给定数字K,我们希望重新格式化字符串,以使每个组恰好包含K个字符,但第一个组可以短于K,但仍必须包含至少一个字符。此外,两组之间必须插入破折号,并且所有小写字母都应转换为大写。

给出一个非空字符串S和一个数字K,根据上述规则格式化字符串。

示例1:输入:S =“ 5F3Z-2e-9-w”,K = 4

输出:“ 5F3Z-2E9W”

说明:字符串S已分为两部分,每个部分有4个字符。请注意,不需要多余的两个破折号,可以将其删除。范例2:输入:S =“ 2-5g-3-J”,K = 2

输出:“ 2-5G-3J”

说明:字符串S已分为三部分,除第一部分外,每个部分都有2个字符,因为如上所述它可能会更短。注意:字符串S的长度将不超过12,000,并且K为正整数。字符串S仅由字母数字字符(a-z和/或A-Z和/或0-9)和破折号(-)组成。字符串S为非空。

我编写了以下代码:

const licenseKeyFormatting = (S, K) => {
    //convert to array, remove special characters, and capitalize
    let s = [...S.replace(/\W/g, '').toUpperCase()]
    let pos = 1
    //from end of array add '-' for every K
    for (let i = s.length - 1; i > 0; i--) {
        if (pos === K) {
            s.splice(i, 0, '-')
            pos = 1
            i-- //re-index bc adding to the array
        }
        pos++
    }
    return s
}


console.log(licenseKeyFormatting("5F3Z-2e-9-w", 4)) //5F3Z-2E9W
console.log(licenseKeyFormatting("2-5g-3-J", 2)) //2-5G-3J
console.log(licenseKeyFormatting("a-a-a-a-", 1)) // this test case fails should be A-A-A-A, I am getting AAA-A

我很确定我逻辑上的缺陷是由于重新索引,但是我不知道如何解决它。

javascript string algorithm for-loop splice
1个回答
0
投票

我的方式。...

function licenseKeyFormatting( S, K )
  {
  let arr = [...S.replace(/\W/g, '').toUpperCase()]
    , p   = 0
    ;
  for (let i=arr.length;i--;)
    {
    p = ++p % K                     // p = (p+1) % K
    if (!p&&i) arr.splice(i,0,'-')  // if p===0 and i>0
    }
  return arr.join('')
  }


console.log(licenseKeyFormatting("5F3Z-2e-9-w", 4)) // 5F3Z-2E9W
console.log(licenseKeyFormatting("2-5g-3-J", 2))   //  2-5G-3J
console.log(licenseKeyFormatting("a-a-a-a-", 1))  //   A-A-A-A  
© www.soinside.com 2019 - 2024. All rights reserved.