題目:
字符串有三種編輯操作:插入一個字符、刪除一個字符或者替換一個字符。 給定兩個字符串,編寫一個函數判定它們是否只需要一次(或者零次)編輯。
示例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;
}
};