【发布时间】:2017-05-12 02:06:20
【问题描述】:
鉴于此输入 s1 = "dadxx" s2 = "ddxx" 我希望输出包含一堆 a,b 对,只要 s1 中的每个字符与 s2 中的字符匹配,反之亦然(允许重复)。这些对中有0,0,因为s1[0] 和s2[0] 都等于d。
问题是我的输出不包含2,1,即使s1[2] 和s2[1] 都等于d。
有人可以修复我的算法或做出更好的算法吗?
Here's a JSFiddle 如果有帮助的话。
这是我的代码:
// For each char, see if other string contains it
s1 = 'dadxx'
s2 = 'ddxx'
matchChars(s1,s2)
matchChars(s2,s1)
function matchChars(a,b) {
for (i = 0; i < a.length; i++) {
found = b.indexOf(a[i])
if (found >= 0) {
if (a===s1) console.log(i,found)
else console.log(found,i)
}
}
}
【问题讨论】:
-
如果你把它们分成一个字符数组,我想array intersection 可能是你想要的?
-
@CrayonViolent 谢谢,但这更像是一个出色的数组交集,可以找到所有匹配项并返回它们的索引
标签: javascript algorithm