V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
ciddechan
V2EX  ›  JavaScript

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

  •  
  •   ciddechan · 2021-07-08 16:57:39 +08:00 · 1568 次点击
    这是一个创建于 994 天前的主题,其中的信息可能已经有所发展或是发生改变。
    如果 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
    }
    }
    6 条回复    2021-07-14 15:04:40 +08:00
    anzerwall
        1
    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
        2
    onlyzdd  
       2021-07-08 19:18:09 +08:00
    leetcode 是个好东西
    ZhaoHuiLiu
        3
    ZhaoHuiLiu  
       2021-07-09 09:04:06 +08:00 via Android
    用 webassembly 写吧,速度很快的
    ciddechan
        4
    ciddechan  
    OP
       2021-07-09 09:11:15 +08:00
    const scramble = (str1, str2) =>
    [...str2].every(val => str2.split(val).length <= str1.split(val).length);
    dayeye2006199
        5
    dayeye2006199  
       2021-07-09 13:12:22 +08:00
    搞两个字典,对每一个字母计数,然后比较两个字典的字母计数。
    复杂度 n log n
    ragnaroks
        6
    ragnaroks  
       2021-07-14 15:04:40 +08:00
    如果你需要大小写匹配,可以做计数器;反之,直接用你的子字符串做分隔
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5313 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:00 · PVG 14:00 · LAX 23:00 · JFK 02:00
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.