字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
示例 1:
输入: first = "pale" second = "ple" 输出: True
示例 2:
输入: first = "pales" second = "pal" 输出: False
来源:力扣(LeetCode)
解题思路
① 先将s1和s2的大小关系控制为s1>s2(方便后面判断) ② 判断s1-s2>1,大于一则代表一次编辑不行直接false ③ 判断s1=s2,对位进行比较,差异>1则返回false ④ 判断s1-s2<=1,难点.假设一个偏移量当s1某位与s2对位不一样时,将偏移量+1,并给s1的索引+偏移量,当偏移量>=2时,返回false ⑤ 当这些都执行完,肯定就满足一次编辑,直接返回true
public static boolean oneEditAway2(String first, String second) {
//获取长度
int ft = first.length(), sc = second.length();
System.out.println("sc"+sc);
System.out.println("ft"+ft);
//判断 保证first>second
if (ft 1) {
return false;
}
//判断相同长度
if (ft == sc) {
//对位判断
int num = 0;
for (int i = 0; i < ft; i++) {
if (first.charAt(i) != second.charAt(i)) {
num++;
}
}
return num <= 1;
}
int i = 0, ofs = 0;
// 遍历两字符串,统计“对应索引处字符不同”数量
while (i < sc) {
if (first.charAt(i+ofs) != second.charAt(i)) {
if (++ofs > 1)
return false;
} else {
i += 1;
}
}
return true;
}



