面试题 01.05. 一次编辑
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = "pale"
second = "ple"
输出: True
思路
分情况讨论:
长度差超过2 肯定错
len1==len2 可能是替换
len1>len2 是删除, len1<len2就是插入(也就是seconen 删除 first)
class Solution {
public:
bool oneEditAway(string first, string second) {
int len1=first.length(), len2=second.length();
if(abs(len1-len2)>1) return false; //长度差超过2
if(len1==len2) return judge(first, second, false);
if(len1>len2) return judge(first, second, true);
else return judge(second, first, true);
}
private:
bool judge(string first, string second, bool function){
// first.length >= seconed.length; function is true: delete, false:replace
bool flag=false;//记录是否已经出现不同的字符
int j=0;
for(int i=0;i<first.length();i++){
if(first[i]!=second[j]){
if(flag) return false;
flag = true;
if(function) j--;//替换的就不j--;删除才j--
}
j++;
}
return true;
}
};