众所周知,力扣的题目都很骚!!!!
今天的题目格外有趣,你要是不注意看,又是两三小时的无尽深渊(没错,又是我陷入进去了!)
来分析题目:
1.它说只进行一次:删除、插入、或者替换
2.给了俩字符串
3.首先我们就想,如果这俩字符串相等是什么原因?很显然,就是替换
4.a>b呢?对!没错!就是删除
5.a<b就是插入对吧!
6.题说只用了一次编辑就是true两次及其以上就是fals,所以我们就长字符减去短字符如果>=2,就是fals,就不用执行了。话不多说,上代码!!
class Solution {
public boolean oneEditAway(String str1, String str2) {
boolean f = false;
int alen = str1.length();
int blen = str2.length();
if (alen == 0 || blen == 0) {
return true;
}
if (alen > blen) {
if (alen - blen >= 2) {
return false;
}
char c1 = str1.charAt(0);
char c2 = str2.charAt(0);// 删除
if (c1 == c2) {
String st = str1.substring(0, blen);
System.out.println(st);
if (!st.equals(str2)) {
return false;
}
} else {
if (alen - blen >= 2) {
return false;
}
String st = str1.substring(1);
if (!st.equals(str2)) {
return false;
}
}
return true;
} else if (alen < blen) {// 添加
int c = 0;
int d = 0;
int cont = 0;
while (d != alen) {//别忘了,它可以在中间给你插入一个字符,也是true哦
if (!(str1.charAt(d) == str2.charAt(c))) {
cont++;
c++;
} else {
c++;
d++;
}
if (cont >= 2) {
return false;
}
}
if (blen - alen >= 2) {
return false;
}
return true;
} else {// 替换
if (str1.equals(str2)) {
return true;
}
int cont = 0;
for (int i = 0; i < alen; i++) {
if (!(str1.charAt(i) == str2.charAt(i))) {
cont++;
if (cont >= 2) {
return false;
}
}
}
return true;
}
}
}
上面要注意的是:
在删除的时候:可以在删除前面一个,也可以删除后面一个
在添加的时候:可以在前、中、后各添加,要注意哦!