javascript - 代码信号上的常见字符计数挑战
问题描述
当我遍历两个数组时,大多数测试都通过了。其中一个测试会产生一个问题,因为即使删除了匹配的元素,嵌套循环也会继续针对第一个循环。
输入:s1:“abca” s2:“xyzbac”
这是我的代码:
function commonCharacterCount(s1, s2) {
const arrayOne = s1.split("")
const arrayTwo = s2.split("")
var matches = [];
for (let i = 0; i < arrayOne.length; i++) {
for (let j = 0; j < arrayTwo.length; j++) {
console.log(arrayTwo[j],arrayOne[i], matches)
if (arrayOne[i] === arrayTwo[j]) {
matches.push(arrayOne[i])
arrayOne.splice(arrayOne[i], 1)
}
}
}
return matches.length
}
我检查了测试 3 上的控制台日志,这是唯一失败的日志,我可以看到跳过第二项“b”时出现问题。
解决方案
Since you are slicing arrayOne you remove an item from arrayOne and this means that it will skip over an item because the variable i gets incremented by 1 but the arrayOne loses an item. So you get something like this.
arrayOne = ["a","b","c","d"]
i = 0
arrayOne[i] results to "a"
now you find a match with arrayTwo and you slice arrayOne at the index i of your match so arrayOne becomes
arrayOne = ["b","c","d"]
//however you still increment i by one so i becomes
i = 1
//so now arrayOne[i] becomes
arrayOne[i] results to "c"
Now I'm not sure my explanation is any good but I have two solutions. 1 doesn't splice and the other does but when it does it decrements i by one.
option 1
function commonCharacterCount(s1, s2) {
const arrayOne = s1.split("")
const arrayTwo = s2.split("")
var matches = [];
for (let i = 0; i < arrayOne.length; i++) {
for (let j = 0; j < arrayTwo.length; j++) {
console.log(arrayTwo[j],arrayOne[i], matches)
if (arrayOne[i] === arrayTwo[j]) {
matches.push(arrayOne[i])
}
}
}
return matches.length
}
option 2
function commonCharacterCount(s1, s2) {
const arrayOne = s1.split("")
const arrayTwo = s2.split("")
var matches = [];
for (let i = 0; i < arrayOne.length; i++) {
for (let j = 0; j < arrayTwo.length; j++) {
console.log(arrayTwo[j],arrayOne[i], matches)
if (arrayOne[i] === arrayTwo[j]) {
matches.push(arrayOne[i])
arrayOne.splice(arrayOne[i], 1)
i--
}
}
}
return matches.length
}
推荐阅读
- django - 如果 get_or_created 插入数据,则返回 id,django
- git - 如何在执行 git 模块时解决剧本错误
- css - 是什么导致 Edge 浏览器上的切换失败?
- php - laravel api 和 web 中的请求文件有什么行为差异吗?
- c# - 使用 C# 进行 TDD,使用模拟编写测试时出现问题
- html - HTML:为什么有这么多类名
- vue.js - process.env.variable 在本地开发中工作,但在部署到 heroku 后,它在 nuxt.js 中不起作用
- swift - SwiftUI NSData 比较实际上是可选的非可选值
- codenameone - 代号:共享文件会导致目标应用程序选择对话框为空
- javascript - 我应该如何处理 Next js 中的新版本?