在从数组末尾循环并在适当位置添加字符后,在重新索引数组时遇到问题



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

您将获得一个以字符串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的长度不会超过12000,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

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

您不应该更改索引。使用splice插入一个元素会将其他元素向后推,但由于从后到前进行迭代,所以这并不重要。您已经处理了移位的元素。

另一个问题是在循环中设置pos = 1。紧接着是pos++。因此,当pos达到K时,pos的值将在循环结束时重置为2。设置pos = 0(在循环中(使其在1上结束,或者将pos++移动到else部分。

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 = 0
}
pos++
}
return s.join("") // <- added join for cleaner console output
}
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

我的方式。。。。

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

OR:(更简单(

function licenseKeyFormatting( S, K )
{
let arr = [...S.replace(/W/g, '').toUpperCase()];
for (let p=arr.length-K;p>0;p-=K) arr.splice(p,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