There are three editing operations for strings: insert an English character, delete an English character, or replace an English character. Given two strings, write a function to determine whether they require only one (or zero) edits.
Example 1:
Input:
first = "pales"
second = "ple"
Output: True
Example 2:
Input:
first = "pales"
second = "pal"
Output: False
The diagram is as follows:
var oneEditAway = function(first, second) {
// 检查长度
if(Math.abs(first.length - second.length) > 1) return false
// 零编辑
if (first === second) return true
//
if (first.length > second.length) {
[second, first] = [first, second]
}
for (let i = 0, len = first.length; i < len; i++) {
if (first[i] !== second[i]) {
return first.slice(i + 1) === second.slice(i + 1) // 字符串长度相等
|| first.slice(i) === second.slice(i + 1) // 字符串不等
}
}
return true
};
// 解法2 ,这个比较蛮力,逻辑没有合并起来
var oneEditAway = function(first, second) {
if(first.length == second.length) {// 替换
return oneEditReplace(first,second)
}else if(first.length+1 == second.length) { // 删除
return oneEditInsert(first,second)
}else if(first.length-1 == second.length) { // 插入
return oneEditInsert(second,first)
}
return false
};
var oneEditReplace = function(first,second) {
var findDif = false
for(var i=0;i<first.length;i++) {
if(first.charAt(i)!=second.charAt(i)) {
if(findDif) return false
findDif = true
}
}
return true
};
var oneEditInsert = function(first,second) {
var index1 = 0
var index2 = 0
while(index2 < second.length && index1 < first.length) {
if(first.charAt(index1) != second.charAt(index2)) {
if(index1 != index2) {
return false
}
} else {
index1++
}
index2++
}
return true
}
// 执行结果:通过显示详情
// 执行用时:72 ms, 在所有 TypeScript 提交中击败了78.95%的用户
// 内存消耗:43.8 MB, 在所有 TypeScript 提交中击败了76.32%的用户
// 通过测试用例:1146 / 1146
function oneEditAway(first: string, second: string): boolean {
if(first.length > second.length + 1 || first.length < second.length - 1) return false
if(first.length === second.length) {
if(first === second) return true
let cut = 0
for(let i = 0; i < first.length; i++){
if(first[i] !== second[i]) cut++
if(cut > 1) return false
}
return true
}else{
const flag = first.length > second.length
let long = flag ? first : second,
short = flag ? second : first,
temp = ''
for(let i = 0; i < long.length; i++){
if(long[i] !== short[i]){
if(temp + long[i] + short.substring(i) === long || temp + long.substring(i + 1) === short) return true
else return false
}
temp += long[i]
}
}
};