https://leetcode-cn.com/problems/one-away-lcci/
难度中等35收藏分享切换为英文关注反馈
字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入:
first = "pale"
second = "ple"
输出: True
示例 2:
输入:
first = "pales"
second = "pal"
输出: False
执行用时:128 ms
内存消耗:39.7 MB
/**
* @param {string} first
* @param {string} second
* @return {boolean}
*/
var oneEditAway = function (first, second) {
if (Math.abs(first.length - second.length) > 1) return false;
if (first.length == second.length) { //替换
for (var i = 0; i < first.length; i++) {
if (first[i] != second[i]) {
first = first.slice(0, i) + first.slice(i + 1, first.length);
second = second.slice(0, i) + second.slice(i + 1, second.length);
break;
}
}
}
//first = second + 1
if (first.length - second.length == -1) {
var temp = first;
first = second;
second = temp;
}
if (first.length - second.length == 1) {
for (var i = 0; i < first.length; i++) {
if (first[i] != second[i]) {
first = first.slice(0, i) + first.slice(i + 1, first.length);
}
}
}
if (first == second) return true;
else return false;
};
执行用时:120 ms
内存消耗:39.6 MB
/**
* @param {string} first
* @param {string} second
* @return {boolean}
*/
var oneEditAway = function (first, second) {
if (Math.abs(first.length - second.length) > 1) return false;
for (var i = 0; i < Math.max(first.length,second.length); i++) {
if (first[i] != second[i] && first.length == second.length) {
first = first.slice(0, i) + first.slice(i + 1, first.length);
second = second.slice(0, i) + second.slice(i + 1, second.length);
break;
}
if (first[i] != second[i] && first.length - second.length == 1) {
first = first.slice(0, i) + first.slice(i + 1, first.length);
break;
}
if (first[i] != second[i] && first.length - second.length == -1) {
second = second.slice(0, i) + second.slice(i + 1, second.length);
break;
}
}
if (first == second) return true;
else return false;
};
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/69275.html