4

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

准确地说,我有一个 std::list 的 std::strings (或 QT 等价物,也可以)

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"

如果我能计算出最长的公共子序列,我可以把它剪掉并再次运行算法以获得第二长的,所以基本上这归结为:

是否有(参考?)实现来计算 std::strings 的 std::list 的 LCS?


这不是一个好的答案,而是我拥有的一个肮脏的解决方案 - 对 QUrls 的 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;
}
4

1 回答 1

1

如果如您所说的后缀树太重或不切实际,那么以下相当简单的蛮力方法可能足以满足您的应用程序。

我假设不同的子串应该是不重叠的,并且是从左到右挑选的。

即使有这些假设,也不需要包含一组字符串的“ N​​ 个不同的最长公共子字符串”的唯一集合。无论N是什么,都可能有超过N个不同的公共子串,它们都具有相同的最大长度,并且从中选择N将是任意的。因此,该解决方案找到最长的不同公共子串的最多N *sets*,其中所有相同长度的公共子串都是一组。

算法如下:

  • Q是长度的目标配额。

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

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

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

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

  • 查找Strings的任何最短成员;保留它的副本S并将其从Strings中删除。我们继续比较S的子串和Strings的子串,因为 { Strings , S }的所有公共子串都必须是S的子串。

  • 使用由偏移量和长度控制的明显嵌套循环迭代生成S的所有子字符串,最长优先。对于 S的每个子串ss

    • 如果ss不是 Strings 的公共子字符串,则下一步。

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

    • ss是与现有的任何子字符串不同的常见子字符串。迭代 Results[l] for l < ss的长度,删除作为ss子串的每个结果,因为所有这些结果都比ss短并且与它没有区别。ss现在是一个公共子字符串,与任何已经在手的子字符串不同,并且所有其他仍在手的子字符串都与ss不同。

    • 对于l = ss的长度,检查Results[l]是否存在,即手头是否有与ss长度相同的结果。如果不是,则称其为NewLength条件。

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

    • 如果StickOrRaise获得,则将ss的长度与l = 手头最短结果的长度进行比较。如果ssl短 ,那么它对于我们的配额来说太短了,所以接下来。如果ssl长,那么手头的所有最短结果都将被ss 淘汰,因此删除 Results[l]并减少N

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

    • 如果NewLength获得,则增加N

    • 放弃对S的具有相同偏移量但更短的子串的内部迭代,因为它们都与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 构建)

于 2013-12-30T17:47:33.063 回答