字符串有三种编辑操作:插入一个英文字符、删除一个英文字符或者替换一个英文字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入: first = "pale" second = "ple" 输出: True示例 2:
输入: first = "pales" second = "pal" 输出: False
/**
* @param {string} first
* @param {string} second
* @return {boolean}
*/
var oneEditAway = function(first, second) {
if(Math.abs(first.length-second.length)>1)return false;
let i = 0;
let j = 0;
let edit = false;
while(i<first.length&&j<second.length){
if(first.charAt(i)===second.charAt(j)){
i++;
j++;
}else{
if(!edit){
if(first.length===second.length){
i++;
j++;
}else if(first.length<second.length){
j++;
}else{
i++;
}
edit = true;
}else{
return false;
}
}
}
return true;
};