[IT 邦帮忙] 优化或重写方法,使计算长字符串时尽可能缩短运算时间

2021-07-08 16:57:39 +08:00
 ciddechan
如果 str1 包含 str2 的所有字母(包括数量),为真,反之为假

function scramble(str1, str2) {
let s1 = str1.split("").sort()
let s2 = str2.split("").sort()
let n = 0
s2.forEach(e=>{
let index = s1.indexOf(e)
if(index>-1){
n++
s1.splice(index,1)
}
})

if(n==s2.length && n!=0){
return true
}else{
return false
}
}
1601 次点击
所在节点    JavaScript
6 条回复
anzerwall
2021-07-08 19:10:51 +08:00
function scramble(str1, str2) {
const counter = Array.from(str1).reduce((p, c) => {p[c] = (p[c] || 0) + 1; return p;}, {})
for (const c of str2) {
if (!counter[c]) return false;
counter[c]--;
}
return true
}
onlyzdd
2021-07-08 19:18:09 +08:00
leetcode 是个好东西
ZhaoHuiLiu
2021-07-09 09:04:06 +08:00
用 webassembly 写吧,速度很快的
ciddechan
2021-07-09 09:11:15 +08:00
const scramble = (str1, str2) =>
[...str2].every(val => str2.split(val).length <= str1.split(val).length);
dayeye2006199
2021-07-09 13:12:22 +08:00
搞两个字典,对每一个字母计数,然后比较两个字典的字母计数。
复杂度 n log n
ragnaroks
2021-07-14 15:04:40 +08:00
如果你需要大小写匹配,可以做计数器;反之,直接用你的子字符串做分隔

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/788339

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX