05 一次编辑
一次编辑
题目描述
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入: first = “pale” second = “ple” 输出: True
示例 2:
输入: first = “pales” second = “pal” 输出: False
代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {string} first
* @param {string} second
* @return {boolean}
*/
var oneEditAway = function (first, second) {
if (first === second) return true;
const length1 = first.length;
const length2 = second.length;
if (Math.abs(length1 - length2) > 1) return false;
if (length1 === length2) {
// 长度一致时,尝试替换字符
let wrongSize = 0;
for (let i = 0; i < length1; i++) {
if (first[i] !== second[i]) wrongSize++;
}
return wrongSize === 1;
} else {
let wrongIndex = 0;
// 长度不一致时,尝试添加或删除一个字符
for (let i = 0; i < Math.max(length1, length2); i++) {
if (first[i] !== second[i]) {
wrongIndex = i;
break;
}
}
return (
first.slice(0, wrongIndex) + first.slice(wrongIndex + 1) === second ||
first === second.slice(0, wrongIndex) + second.slice(wrongIndex + 1)
);
}
};
本文由作者按照
CC BY 4.0
进行授权