题目:
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例1:
输入:
first = "pale"
second = "ple"
输出: True
示例二:
输入:
first = "pales"
second = "pal"
输出: False
代码:
class Solution {
public:
bool oneEditAway(string first, string second)
{
int l1 = first.size();
int l2 = second.size();
//sort(first.begin(), first.end());
//sort(second.begin(), second.end());
if(l1 - l2 > 1 || l2 - l1 >1)
return false;
if((l1-l2 ==0 || l2-l1 ==0) && l1 != 1)
{
if(first == second)
return true;
else
return false;
}
if((l1 ==1 && l2 ==0) ||(l1==0 && l2 ==1) ||(l1 ==l2 ==1))
return true;
if(l1 -l2 ==1)
{
for(int i =0; i< l1; i++)
for(int j =0; j < l2; j++)
{
if(first[i] != second[j])
{
char s = first[i];
second.insert(j,&s);
if(first == second) {return true;}
}
else
return false;
}
}
else if(l2 -l1 == 1)
{
for(int i =0; i< l2; i++)
for(int j =0; j < l1; j++)
{
if(second[i] != first[j])
{
second.erase(second[i]);
if(first == second) {return true;}
}
else if(second[i] == first[j])
{ second.erase(second[l2-1]);
if(first == second) {return true;}
}
else
return false;
}
}
return 0;
}
};
本人没有想到绝对值函数简直惭愧!!借鉴的优秀解法如下:
class Solution {
public:
bool oneEditAway(string first, string second) {
if(first==second){
return true;
}
const int len1=first.size();
const int len2=second.size();
if(abs(len1-len2)>1){
return false;
}
int i=0,j=len1-1,k=len2-1;
while(i<len1 && i<len2 && first[i]==second[i]){ // i从左至右扫描
++i;
}
while(j>=0 && k>=0 && first[j]==second[k]){ // j、k从右至左扫描
--j;
--k;
}
return j-i<1 && k-i<1;
}
};