c++ - 如何检查两个字符串是否“不管一个字符”是否相等?
问题描述
我想检查两个字符串是否相等,无论缺少一个字符。例如“HappyMan”等于“HappyMn”和“HappyMann”和“HappyMnn”。是否有任何内置功能来执行此任务?我试图对它们进行排序,然后计算有多少字符不同,但它不起作用。这是我的代码
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
int cnt = 0;
for (int i = 0; i < a.length(); i++) {
if (a[i] != b[i])
cnt++;
if (cnt > 1) {
cout << "Not equal";
return 0;
}
}
cout << "Equal";
return 0;
}
解决方案
#include <iostream>
#include <string>
int main()
{
std::string str1 = "manatee";
std::string str2 = "mannatee";
std::string strLong = "";
std::string strShort = "";
if (str1.length() >= str2.length()){
strLong = str1;
strShort = str2;
}
else{
strLong = str2;
strShort = str1;
}
if (strLong.length() - strShort.length() > 1){
printf("%s", "They are not equal.");
return false;
}
bool firstDifference = true;
for (int i = 0; i < strShort.length(); i++){
if (strShort[i] != strLong[i] && firstDifference){
if (strLong.length() > strShort.length()){
strLong = strLong.substr(0, i) + strLong.substr(i+1, strLong.length() - i
- 1);
}
firstDifference = false;
continue;
}
else if (strShort[i] != strLong[i] && !firstDifference) {
printf("%s", "They are not equal");
return false;
}
}
printf("%s", "They are equal");
return true;
}
推荐阅读
- red-black-tree - 插入红黑树
- yaml - YAML 中的索引数组是什么?
- python - 我无法使用 python 从电子表格上的电子邮件列表中发送电子邮件
- python - RPLidarException:描述符起始字节不正确
- c# - 使用 SHA256 生成摘要并使用 RSA C# 将其作为字符串导入密钥进行签名
- python - 显示文本数据 - 在 python 中交互
- jenkins - 错误 .groovy 文件在工作区 jenkins 中不存在
- python - 如何在if条件内的列表上进行循环
- version - R 4.0.5 是精简版吗?
- mysql - SQLSTATE [42S22]:找不到列:1054 '字段列表'中的未知列'p.id'