两个以上字符串中最长的公共子字符串-C++

Longest common substring from more than two strings - C++

本文关键字:字符串 -C++ 两个      更新时间:2023-10-16

我需要从C++中的一组文件名中计算最长的公共子字符串。

确切地说,我有一个std::string列表(或者QT等价物,也可以是fine)

char const *x[] = {"FirstFileWord.xls", "SecondFileBlue.xls", "ThirdFileWhite.xls", "ForthFileGreen.xls"};
std::list<std::string> files(x, x + sizeof(x) / sizeof(*x));

我需要计算所有字符串的n个不同的最长公共子字符串,在这种情况下,例如,对于n=2

 "File" and ".xls"

如果我能计算出最长的公共子序列,我可以把它去掉,然后再次运行算法,得到第二长的子序列,所以本质上可以归结为:

是否有(reference?)实现用于计算std::字符串的std::列表的LCS?


这不是一个好答案,但我有一个肮脏的解决方案——对一个Qrls的QList使用暴力,只从中提取最后一个"/"之后的部分。我很想用"正确"的代码来代替它。

(我发现http://www.icir.org/christian/libstree/-这会有很大帮助,但我无法在我的机器上编译它。也许有人用过这个?)

QString SubstringMatching::getMatchPattern(QList<QUrl> urls)
    {
    QString a;
    int foundPosition = -1;
    int foundLength = -1;
    for (int i=urls.first().toString().lastIndexOf("/")+1; i<urls.first().toString().length(); i++)
    {
        bool hit=true;
        int xj;
        for (int j=0; j<urls.first().toString().length()-i+1; j++ ) // try to match from position i up to the end of the string :: test character at pos. (i+j)
        {
            if (!hit) break;
            QString firstString = urls.first().toString().right( urls.first().toString().length()-i ).left( j ); // this needs to match all k strings
            //qDebug() << "SEARCH " << firstString;
            for (int k=1; k<urls.length(); k++) // test all other strings, k = test string number
            {
                if (!hit) break;
                //qDebug() << " IN  " << urls.at(k).toString().right(urls.at(k).toString().length() - urls.at(k).toString().lastIndexOf("/")+1);
                //qDebug() << " RES " << urls.at(k).toString().indexOf(firstString, urls.at(k).toString().lastIndexOf("/")+1);
                if (urls.at(k).toString().indexOf(firstString, urls.at(k).toString().lastIndexOf("/")+1)<0) {
                    xj = j;
                    //qDebug() << "HIT LENGTH " << xj-1 << " : " << firstString;
                    hit = false;
                }
            }
        }
        if (hit) xj = urls.first().toString().length()-i+1; // hit up to the end of the string
        if ((xj-2)>foundLength) // have longer match than existing, j=1 is match length
        {
            foundPosition = i; // at the current position
            foundLength = xj-1;
            //qDebug() << "Found at " << i << " length " << foundLength;
        }
    }
    a = urls.first().toString().right( urls.first().toString().length()-foundPosition ).left( foundLength );
    //qDebug() << a;
    return a;
}

如果后缀树太重或不切实际,请执行以下操作对于您的应用程序来说,相当简单的暴力方法可能就足够了。

我认为不同的子字符串应该是不重叠的,并且是从从左到右。

即使有这些假设,也不需要有一个唯一的集合一组字符串的"N不同的最长公共子字符串"。无论N是什么,可能存在多个N不同的公共子串,所有子串都具有相同的极大值长度以及从它们中选择N的任何选项都是任意的。照着该解决方案最多可找到最长不同公共的N*集合所有长度相同的子字符串都是一个集合。

算法如下:

  • Q是长度的目标配额。

  • 字符串是字符串的问题集。

  • Results是一个最初为空的多映射,它将长度映射到一组字符串,结果[l]是长度l的集合

  • N,最初为0,是结果中表示的不同长度的数量

  • 如果Q为0或字符串是空,则返回结果

  • 查找字符串中任何最短的成员;保留它的副本S并将其删除来自字符串。我们将S的子串与因为{StringsS的子串。

  • 使用明显的嵌套循环由偏移和长度控制。对于的每个子字符串ssS:

    • 如果ss不是Strings的公共子字符串,那么接下来。

    • 迭代结果[l]对于l>=ss的长度,直到结果或直到ss被发现是检查的子串后果在后一种情况下,ss与已经存在的结果没有区别在手,所以接下来。

    • ss是一个常见的子字符串,与现有的子字符串不同。迭代l<ss的长度,删除作为ss的子串,因为所有这些都比ss短,并且不明显ss现在是一个常见的子字符串,与现有的子字符串不同,并且所有其他留在手上的都不同于ss

    • 对于l=ss的长度,检查是否存在Results[l],即如果手头有任何与ss长度相同的结果。如果没有,就这么说吧NewLength条件。

    • 还要检查N=Q,即我们是否已经达到不同长度。如果NewLength获得并且N==Q,则将其称为StickOrRaise条件。

    • 如果StickOrRaise获得,则将ss的长度与l=手中有最短的长度。如果ss短于l那么它对我们的配额来说太短了,所以下一个。如果ssl长那么所有手头最短的结果都将被推翻,支持ss,因此删除结果[l]和减量N

    • ss插入按长度键入的结果中。

    • 如果获得NewLength,则递增N

    • 放弃S中具有ss的偏移量相同,但更短,因为它们都不不同来自ss

    • 将外部迭代的S中的偏移量提前ss的长度,到下一个不重叠子串的开始。

  • 返回结果

下面是一个实现该解决方案的程序,并用字符串列表:

#include <list>
#include <map>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
// Get a non-const iterator to the shortest string in a list
list<string>::iterator shortest_of(list<string> & strings)
{
    auto where = strings.end();
    size_t min_len = size_t(-1);
    for (auto i = strings.begin(); i != strings.end(); ++i) {
        if (i->size() < min_len) {
            where = i;
            min_len = i->size();
        }
    }
    return where;
}
// Say whether a string is a common substring of a list of strings
bool 
is_common_substring_of(
    string const & candidate, list<string> const & strings)
{
    for (string const & s : strings) {
        if (s.find(candidate) == string::npos) {
            return false;
        }
    }
    return true;
}

/* Get a multimap whose keys are the at-most `quota` greatest 
    lengths of common substrings of the list of strings `strings`, each key 
    multi-mapped to the set of common substrings of that length.
*/
multimap<size_t,string> 
n_longest_common_substring_sets(list<string> & strings, unsigned quota)
{
    size_t nlengths = 0;
    multimap<size_t,string> results;
    if (quota == 0) {
        return results;
    }
    auto shortest_i = shortest_of(strings);
    if (shortest_i == strings.end()) {
        return results;
    }
    string shortest = *shortest_i;
    strings.erase(shortest_i);
    for ( size_t start = 0; start < shortest.size();) {
        size_t skip = 1;
        for (size_t len = shortest.size(); len > 0; --len) {
            string subs = shortest.substr(start,len);
            if (!is_common_substring_of(subs,strings)) {
                continue;
            }
            auto i = results.lower_bound(subs.size());
            for (   ;i != results.end() && 
                    i->second.find(subs) == string::npos; ++i) {}
            if (i != results.end()) {
                continue;
            }
            for (i = results.begin(); 
                    i != results.end() && i->first < subs.size(); ) {
                if (subs.find(i->second) != string::npos) {
                    i = results.erase(i);
                } else {
                    ++i;
                }
            }
            auto hint = results.lower_bound(subs.size());
            bool new_len = hint == results.end() || hint->first != subs.size();
            if (new_len && nlengths == quota) {
                size_t min_len = results.begin()->first;
                if (min_len > subs.size()) {
                    continue;
                }
                results.erase(min_len);
                --nlengths;
            }
            nlengths += new_len;
            results.emplace_hint(hint,subs.size(),subs);
            len = 1;
            skip = subs.size();
        }
        start += skip;
    }
    return results; 
}
// Testing ...
int main()
{
    list<string> strings{
        "OfBitWordFirstFileWordZ.xls", 
        "SecondZWordBitWordOfFileBlue.xls", 
        "ThirdFileZBitWordWhiteOfWord.xls", 
        "WordFourthWordFileBitGreenZOf.xls"};
    auto results = n_longest_common_substring_sets(strings,4);
    for (auto const & val : results) {
        cout << "length: " << val.first 
        << ", substring: " << val.second << endl;
    }
    return 0;
}

输出:

length: 1, substring: Z
length: 2, substring: Of
length: 3, substring: Bit
length: 4, substring: .xls
length: 4, substring: File
length: 4, substring: Word

(使用gcc 4.8.1构建)