题目描述
思路
分类讨论
假定first和second的长度分别为m和n。
- 如果first和second转换需要一次编辑,则可能有三种情况:
- first插入一个字符得到second,则n-m=1,second比first多一个字符,其余字符都相同;
- first删除一个字符得到second,则m-n=1,first比second多一个字符,其余字符都相同;
- first中的一个字符替换成其他字符得到second,此时m=n,first和second恰有一个字符不同。
- 如果first和second不需要编辑,则m=n且first=second。
具体实现方面: - 当n-m=1或m-n=1时,同时遍历两个字符串,比较对应下标处的字符是否相同,如果字符相同则将字符串的下标同时+1,如果字符不同,只将较长的字符串的下标+1。遍历过程中,如果出现两个字符串的下标之差大于1则不符合一次编辑,遍历结束时,如果两个字符串的下标之差不大于1则符合一次编辑。
- 当m=n时,同时遍历两个字符串,比较相同下标处的字符是否相同,如果字符不同的下标个数不超过1,则符合要求。
Python实现
class Solution:
def oneEditAway(self, first: str, second: str) -> bool:
m, n = len(first), len(second)
if m < n:
return self.oneEditAway(second, first)
if m - n > 1:
return False
for i, (x, y) in enumerate(zip(first, second)):
if x != y:
return first[i+1:] == second[i+1:] if m == n else first[i+1:] == second[i:]
return True
Java实现
class Solution {
public boolean oneEditAway(String first, String second) {
int m = first.length(), n = second.length();
if (n-m==1) {
return func(first, second);
} else if (m - n == 1) {
return func(second, first);
} else if (m == n) {
boolean diff = false;
for (int i = 0; i < m; i++) {
if (first.charAt(i) != second.charAt(i)) {
if (!diff) {
diff = true;
} else {
return false;
}
}
}
return true;
} else {
return false;
}
}
private boolean func(String shorter, String longer) {
int len1 = shorter.length(), len2 = longer.length();
int index1 = 0, index2 = 0;
while (index1 < len1 && index2 < len2) {
if (shorter.charAt(index1) == longer.charAt(index2)) {
index1++;
}
index2++;
if (index2-index1 > 1) {
return false;
}
}
return true;
}
}