How to find Longest Common Substring using C++

前端 未结 7 1953
轮回少年
轮回少年 2020-12-05 07:43

I searched online for a C++ Longest Common Substring implementation but failed to find a decent one. I need a LCS algorithm that returns the substring itself, so it\'s not j

7条回答
  •  無奈伤痛
    2020-12-05 08:27

    I tried several different solutions for this but they all seemed really slow so I came up with the below, didn't really test much, but it seems to work a bit faster for me.

    #include 
    
    std::string lcs( std::string a, std::string b )
    {
        if( a.empty() || b.empty() ) return {} ;
    
        std::string current_lcs = "";
    
        for(int i=0; i< a.length(); i++) {
            size_t fpos = b.find(a[i], 0);
            while(fpos != std::string::npos) {
                std::string tmp_lcs = "";
                tmp_lcs += a[i];
                for (int x = fpos+1; x < b.length(); x++) {
                    tmp_lcs+=b[x];
                    size_t spos = a.find(tmp_lcs, 0);
                    if (spos == std::string::npos) {
                        break;
                    } else {
                        if (tmp_lcs.length() > current_lcs.length()) {
                            current_lcs = tmp_lcs;
                        }
                    }
                }
                fpos = b.find(a[i], fpos+1);
            }
        }
        return current_lcs;
    }
    
    int main(int argc, char** argv)
    {
        std::cout << lcs(std::string(argv[1]), std::string(argv[2])) << std::endl;
    }
    

提交回复
热议问题