作者:翟天保Steven
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处
好久没做题目了,近期刷抖音碰到一个题目,乍一看不是很难,但是手生了,就写个玩玩,大家轻喷。
两个字符串比较,如abcdefg和25abdfxx,返回:位置0多出:25;位置2缺少:c;位置4缺少:e;位置6错误,应为g。
我看很多人说双指针法、动态规划能解,我暂时没想那么多,就用了简单的双循环+滑动窗口。
#include <iostream>
#include <string>
using namespace std;
void compareStrings(std::string str1, std::string str2) {
int len1 = str1.length();
int len2 = str2.length();
int idx1 = 0;
int idx2 = 0;
for (int i = 0; i < len1; ++i) {
for (int j = idx2; j < len2; ++j) {
if (str1[i] == str2[j]) {
if (j > idx2 && i == idx1) {
cout << "位置" << i << "多出:" << str2.substr(idx2, j - idx2) << endl;
idx1++;
idx2 = j + 1;
}
else if (i > idx1 && j == idx2) {
cout << "位置" << idx1 << "缺少:" << str1.substr(idx1, i - idx1) << endl;
idx1 = i + 1;
idx2++;
}
else if (i > idx1 && j > idx2) {
cout << "位置" << idx1 << "错误,应为:" << str1.substr(idx1, i - idx1) << endl;
idx1 = i + 1;
idx2= j + 1;
}
else{
idx1++;
idx2++;
}
break;
}
}
if (i == (len1 - 1) && (idx1 < len1)) {
cout << "位置" << idx1 << "错误,应为:" << str1.substr(idx1, i - idx1 + 1) << endl;
}
}
}
int main() {
std::string str1 = "abcdefg";
std::string str2 = "25abdfxx";
cout << "字符串1:" << str1 << endl;
cout << "字符串2:" << str2 << endl;
compareStrings(str1, str2);
return 0;
}
字符串如题目要求时,结果如下,可以发现是满足的。
加几个字符再试试,依然可行。
中间内容再打乱一些,暂无问题。
多几个重复字符,按照我的逻辑,输出结果是对的,但不知道题目是不是这意思。
如果代码有什么需要改进的或者有什么bug,欢迎评论留言,我会及时更正以免误导他人~
如果文章帮助到你了,可以点个赞让我知道,我会很快乐~加油!
联系客服