C++求两个字符串的最长子序列

本文介绍了一种求解两个字符串最长公共子序列长度及具体子序列的方法。通过使用两个二维数组分别记录最长子序列的长度和方向,该算法能够递归地找到最长公共子序列。示例代码展示了如何对didactdcal和advantage两个字符串进行处理并输出结果。
摘要由CSDN通过智能技术生成

void lcsLength(string str1, string str2, vector< vector>& intV, vector< vector>& charV)
{
int str1Len = str1.size();
int str2Len = str2.size();
intV.resize(str1Len + 1);
charV.resize(str1Len + 1);
for (int i = 0; i < str1Len + 1; ++i)
{
intV[i].resize(str2Len + 1);
charV[i].resize(str2Len + 1);
}
for (int i = 1; i <= str1Len; ++i) {
for (int j = 1; j <= str2Len; ++j) {
if (str1[i - 1] == str2[j - 1]) {
intV[i][j] = intV[i - 1][j - 1] + 1;
charV[i][j] = ‘c’;
}
else if (intV[i - 1][j] >= intV[i][j - 1]) {
intV[i][j] = intV[i - 1][j];
charV[i][j] = ‘u’;
}
else {
intV[i][j] = intV[i][j - 1];
charV[i][j] = ‘l’;
}
}
}
cout << “subsequence length:” << intV[str1Len][str2Len] << endl;
}
void print_lcs(vector< vector>& charV, string str1, int i, int j)
{
if (i == 0 || j == 0)
return;
if (charV[i][j] == ‘c’) {
print_lcs(charV, str1, i - 1, j - 1);
cout << str1[i - 1];
}
else if (charV[i][j] == ‘u’)
print_lcs(charV, str1, i - 1, j);
else
print_lcs(charV, str1, i, j - 1);
}
int main()
{
string str1 = “didactdcal”;
string str2 = “advantage”;
vector< vector> intV;
vector< vector> charV;
lcsLength(str1, str2, intV, charV);
print_lcs(charV, str1, str1.size(), str2.size());
}

C++中,我们可以使用动态规划的方式来解决这个问题。这里是一个简单的示例程序,用于找到无重复字符的最长序列并按字典序排序: ```cpp #include <iostream> #include <string> #include <vector> #include <algorithm> std::string findPassword(std::string input) { int n = input.size(); std::vector<int> dp(n, 0); std::vector<std::pair<char, int>> pos; for (int i = 0; i < n; ++i) { if (pos.empty() || pos.back().first != input[i]) { pos.push_back({input[i], i}); } else { dp[i] = pos.back().second + 1; pos.pop_back(); } while (!pos.empty() && pos.front().second < i - dp[i]) { pos.pop_front(); } if (pos.empty()) { dp[i] += 1; } else { dp[i] = std::max(dp[i], pos.front().second + 1); } pos.push_front({input[i], i}); } std::string password; for (int i = dp.argmax(); i >= 0; --i) { password += input[i]; } std::sort(password.begin(), password.end()); return password; } int main() { std::string input; std::cout << "请输入原始字符串: "; std::cin >> input; std::string result = findPassword(input); std::cout << "生成的密码: " << result << std::endl; return 0; } ``` 在这个程序中,`dp`数组记录每个位置之前未重复字符所能构成的最长序列长度,`pos`存储当前遍历过程中遇到的新字符及其索引。程序首先初始化,然后逐个字符检查,更新`dp`和`pos`,后将结果字符串排序返回。 运行此程序时,只需输入一个字符串,它会输出经过处理后的密码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值