问题1:给定两个字符串str1和str2,输出两个字符串的最长公共子串,保证str1和str2的最长公共子串存在且唯一。
要求:
(1)数据输入:字符串长度0<|str1|,|str2|≦5000,元素从{0-9,A-Z}随机生成。
(2)数据输出:最长公共子串。
(3)根据代码,分析时间复杂度、空间复杂度,以及实际执行时间、实际占用空间;
代码1:
#include <iostream>
#include <string>
#include <vector>
#include <chrono>
std::string longestCommonSubstring(const std::string& str1, const std::string& str2) {
int len1 = str1.length();
int len2 = str2.length();
// dp[i][j] 表示 str1[0:i-1] 和 str2[0:j-1] 的最长公共后缀的长度
std::vector<std::vector<int>> dp(len1 + 1, std::vector<int>(len2 + 1, 0));
int maxLength = 0; // 最长公共子串的长度
int endIndex = -1; // 最长公共子串在 str1 中的结束位置
for (int i = 1; i <= len1; ++i) {
for (int j = 1; j <= len2; ++j) {
if (str1[i - 1] == str2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
if (dp[i][j] > maxLength) {
maxLength = dp[i][j];
endIndex = i - 1;
}
} else {
dp[i][j] = 0;
}
}
}
// 从 str1 中提取最长公共子串
return str1.substr(endIndex - maxLength + 1, maxLength);
}
int main() {
std::string str1, str2;
std::cin >> str1 >> str2;
system("chcp 65001");
auto start = std::chrono::high_resolution_clock::now();
std::string result = longestCommonSubstring(str1, str2);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end - start;
std::cout << result << std::endl;
std::cout << "排序所需时间: " << duration.count() << " 毫秒" << std::endl;
system("pause");
return 0;
}
结果1:
输入:

输出:

分析1:
最长公共子串的时间复杂度为:O(n*m);
空间复杂度为:O(n*m)。
问题2:给定n个整数组成的序列,现在要求将序列分割为m段,每段子序列中的数在原序列中连续排列。如何分割才能使这m段子序列的和的最大值达到最小?
代码2:
include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <chrono>
using namespace std;
bool canSplit(const vector<int>& nums, int m, int maxSum) {
int currentSum = 0;
int segments = 1;
for (int num : nums) {
if (currentSum + num <= maxSum) {
currentSum += num;
} else {
segments++;
currentSum = num;
if (segments > m) {
return false;
}
}
}
return true;
}
int splitArray(vector<int>& nums, int m) {
int n = nums.size();
int maxElement = *max_element(nums.begin(), nums.end());
int totalSum = accumulate(nums.begin(), nums.end(), 0);
int left = maxElement;
int right = totalSum;
int result = right;
while (left <= right) {
int mid = left + (right - left) / 2;
if (canSplit(nums, m, mid)) {
result = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
int main() {
system("chcp 65001");
int n, m;
cin >> n >> m;
vector<int> nums(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
auto start = std::chrono::high_resolution_clock::now();
int result = splitArray(nums, m);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end - start;
cout << result << endl;
std::cout << "排序所需时间: " << duration.count() << " 毫秒" << std::endl;
system("pause");
return 0;
}
结果2:

分析2:
最小公共子串和的时间复杂度为:O(nlogS),S为序列总和;
空间复杂度为:O(1)。
35万+

被折叠的 条评论
为什么被折叠?



