gpt4 book ai didi

c++ - 查找 blob 中最长的 blob 前缀

转载 作者:行者123 更新时间:2023-11-28 07:20:36 24 4
gpt4 key购买 nike

我尝试在 C++ 中针对以下问题生成/获得有效的实现:

我必须使用 blob (const char *data, size_t length),我称它们为“blob1”和“blob2”。现在我想在“blob1”中获得“blob2”的最长前缀。如果最长的前缀在“blob1”中多次出现,我想获得索引最大的前缀。

这里有一个例子(这里的 blob 只是 ASCII 字符串,所以更容易阅读这个例子):

blob1 = HELLO LOOO HELOO LOOO LOO JU

blob2 = LOOO TUS

以下都是blob2的有效前缀:

{ L, LO, LOO, LOOO, LOOO, LOOO TLOOO TULOOO TUS

blob1blob2的最长前缀是LOOO。它在那里两次:你好 *LOOO *HELOO *LOOO *LOO JU

所以我想获取第二个的索引,即 6,以及前缀的长度,即 4

不幸的是 blob1 和 blob2 改变了很多次,所以创建树或其他一些复杂结构可能很慢。

你知道解决这个问题的好算法吗?

谢谢。

干杯凯文

最佳答案

我不知道这是否是解决此问题的最佳算法(我敢肯定,这不是),但是,我想这是一个很好的算法。想法很简单,首先在 blob1 中搜索 blob2 中最低的标记。找到匹配项后,尝试查看是否可以在该位置匹配更大的标记。如果这是真的,请更新您的 token 长度。

从上一站继续搜索,但此时从 blob2 中搜索具有更新 token 长度的 token 。找到匹配项后,尝试查看是否可以在该位置匹配更大的标记。如果这是真的,请更新您的 token 长度。重复前面的过程,直到缓冲区结束。

Bellow 是一个简单的通量图,试图解释这个算法,然后是一个简单的完整程序,展示了一个实现。

enter image description here

#include <algorithm>
#include <vector>
#include <iostream>

/////////////////////0123456789012345678901234567
const char str1[] = "HELLO LOOO HELOO LOOO LOO JU";
const char str2[] = "LOOO TUS";

int main()
{
std::vector<char> blob1(strlen(str1));
std::vector<char> blob2(strlen(str2));
blob1.reserve(30);
blob2.reserve(30);

std::copy(str1, str1+strlen(str1), blob1.begin());
std::copy(str2, str2+strlen(str2), blob2.begin());

auto next = blob1.begin();
auto tokenLength = 1;
auto position = -1;

while ( std::next(next, tokenLength) < blob1.end() ) {
auto current = std::search(next,
blob1.end(),
blob2.begin(),
std::next(blob2.begin(), tokenLength));

if (current == blob1.end() )
break;

position = std::distance(blob1.begin(), current);
next = std::next(current, 1);

for (auto i = tokenLength; std::next(blob2.begin(), i) < blob2.end(); ++i) {
auto x = std::search(std::next(current, i),
std::next(current, i + 1),
std::next(blob2.begin(), i),
std::next(blob2.begin(), i + 1));
if ( x != std::next(current, i) )
break;

++tokenLength;
}
}

std::cout << "Index: " << position << ", length: " << tokenLength << std::endl;

}

关于c++ - 查找 blob 中最长的 blob 前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19526968/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com