【问题标题】:How to optimize the finding of a specific string as part of a whole string in a large set of strings如何优化在大量字符串中查找特定字符串作为整个字符串的一部分
【发布时间】:2021-02-01 09:57:08
【问题描述】:

我有两个对象数组,我正在尝试优化作为这些对象一部分的两个字符串之间的匹配。

在最坏的情况下,我必须遍历目标数组中的整个对象。

原点数组:

[ {name: "banana 1"}, {name: "banana 2"}, {name: "monkey"}]

目标数组:

[ {title: "this is a banana 1"}, {title: "this doesnt matter"}, {title: "this also doesnt matter"} ]

我必须使用正则表达式为原始数组的每个元素在目标数组上找到匹配项。

在这种情况下,我只有一个匹配项:

香蕉 1 -> 这是香蕉 1

我认为没有比两个循环更好更快的方法了数组。

有什么方法可以改善吗?我想优化它,因为我的数组有很多元素。我一直在尝试找出如何在 postgres 中实现具有相似表达式的索引,也许这可以在某种程度上帮助我。

【问题讨论】:

  • 你必须匹配索引吗?
  • 什么意思?没听懂很抱歉
  • 两个数组中索引为零的匹配项。会不会,匹配在第一个数组中的索引为零,而在第二个数组中的索引为 1000?
  • 是的,这是完全可能的,在最坏的情况下(查找第一个数组中所有元素的匹配项)我需要循环整个第二个数组的次数等于第一个数组的大小跨度>
  • 你只有一场比赛吗?

标签: javascript arrays performance match matching


【解决方案1】:

您可以使用带有下划线_(也可以是Symbol)的Trie 作为属性来表示搜索字符串的结尾。

要获取第一个数组的单词,您可以迭代直到长度(使用排序搜索字符串长度进行优化)并在另一个循环中检查所有字符。如果最后找到结束指示符,你就找到了一个词。

let shortest = Number.MAX_VALUE;

const
    values = [{ name: "banana 1" }, { name: "banana 2" }, { name: "monkey" }],
    destinations = [{ title: "this is a banana 1##with some more text" }, { title: "this doesnt matter" }, { title: "this also doesnt matter" }],
    trie = values.reduce((t, { name }) => {
        if (shortest > name.length) shortest = name.length;
        [...name].reduce((o, k) => o[k] ??= {}, t)._ = true;
        return t;
    }, {}),
    result = destinations.map(({ title }) => {
        for (let i = 0, l = title.length - shortest + 1; i < l; i++) {
            let p = trie;
            for (let j = i; j < title.length; j++) {
                if (!(p = p[title[j]])) break;
                if (p._) return title.slice(i, j + 1);
            }
        }
        return '';
    });
console.log(shortest);
console.log(result);
console.log(trie);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    • 2011-04-14
    • 1970-01-01
    • 2023-01-23
    • 2018-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多