解题思路和代码
/*************************************************************************
> File Name: onceEdit.cpp
> Author: 念念
> Mail: 2845906049@qq.com
> Created Time: 2021年08月26日 星期四 23时11分39秒
> Function: 字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。
给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
************************************************************************/
#include <iostream>
using namespace std;
//思路,修改则需要字符长度相等,对短串插入即为对长串删除。
//只能修改一次,长度差不能大于1
//效果:100% 80.97%
bool onceEdit(string s1,string s2)
{
if(s1 == s2) return true;
short len1 = s1.length();
short len2 = s2.length();
char x = len1 - len2;
if(x > 1) return false;
else if(x == 0)
{
int count = 0; //表示不同的字母数
for(int i = 0; i < len1 && i < len2;i++)
{
if(s1[i] != s2[i])
{
count++;
}
if(count > 1) return false;
}
}
else if(x == 1)
{
int count = 0; //表示不同的字母数
for(int i = 0,j = 0; i < len1; i++,j++)
{
if(s1[i] != s2[j])
{
if(s1[i+1] != s2[j]) return false;
count++;
if(count > 1) return false;
i++;//跳过长串不同的位继续比较
}
}
}
else
{
int count = 0; //表示不同的字母数
for(int i = 0,j = 0; j < len2; i++,j++)
{
if(s1[i] != s2[j])
{
if(s1[i] != s2[j+1]) return false;
count++;
if(count > 1) return false;
j++;//跳过长串不同的位继续比较
}
}
}
return true;
}
int main()
{
//cout << onceEdit("leetcode","leetode") << endl;
cout << onceEdit("teacher","treacher") << endl;
cout << onceEdit("teacher","taches");
return 0;
}