打印所有最长匹配的子字符串

Printing all longest matching substrings

本文关键字:字符串 打印      更新时间:2023-10-16

我有一个任务,用于查找字符串"B D C A B A"和"A B C B D A B"之间所有最长的匹配子字符串。 网上有很多部分解决方案,但没有一个能满足我的需要。 我创建这个是为了找到一个最长的匹配子字符串,但我需要能够找到所有这些子字符串,总共应该有 6 个。

#include <iostream>
#include <string>
#include <vector>
using namespace std;
void myLMS(string one, string two);
int main()
{
string s1 = "ABCBDAB";
string s2 = "BDCABA";
myLMS(s1, s2);
return 0;
}
void myLMS(string one, string two) {
vector<vector<char>> lms;
vector<char> one_lms;
for (int i = 0; i < two.length(); i++) {
for (int j = i + 1; j < one.length(); j++) {
if (two[i] == one[j]) {
one_lms.push_back(two[i]);
break;
}
}
}
lms.push_back(one_lms);
for (int i = 0; i < lms[0].size(); i++) {
cout << lms[0][i];
}
}

有没有办法让我继续使用这种方法并获得我正在寻找的结果,或者是否需要另一种方法?

编辑:我发现这个解决方案 https://www.geeksforgeeks.org/printing-longest-common-subsequence-set-2-printing/但我对仅从程序中复制并不真正感兴趣,因为这对我并没有真正的帮助。 它也只完成了我想要做的一半。

从赋值提示符来看,从此示例打印的前三个字符串以及相同的三个字符串都在那里。 反转字符串不会获得这些向后的子字符串,那么如何计算它们呢?

你的逻辑很不完整。 下面是一些伪代码来帮助你入门。

for each character in string 1
for each character in string 2
if char_1 == char_2
possible substring match 
do the next chars match?
yes
there is a substring - now find longest
no
no substring match, continue the loop

我不明白以这种方式解决它有什么需要,因为你的输入字符串是固定的,你从一个字符串的第一个字符运行循环到最后一个 -1 个字符,如果找到匹配项,则为每个后续字符运行另一个嵌套的 for 循环,就像我们所有人在开始时所做的找出公共子字符串的程序一样。