字符串有三种编辑操作:插入一个字符、删除一个字符或者替换一个字符。 给定两个字符串,编写一个函数判定它们是否只需要一次(或者零次)编辑。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/one-away-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
private boolean judgeReplace(String first, String second) {
int num = 0;
for (int i = 0; i < first.length(); ++i) {
if (first.charAt(i) != second.charAt(i)) {
num++;
if (num > 1) {
return false;
}
}
}
return true;
}
private boolean judgeInsert(String first, String second) {
int p1 = 0, p2 = 0;
boolean inserted = false;
while (p2 < second.length()) {
if (p1 == first.length() || first.charAt(p1) != second.charAt(p2)) {
if (inserted) {
return false;
}
inserted = true;
p2++;
} else {
p1++;
p2++;
}
}
return true;
}
private boolean judgeDelete(String first, String second) {
return judgeInsert(second, first);
}
public boolean oneEditAway(String first, String second) {
if (first.length() == second.length()) {
return judgeReplace(first, second);
} else if (first.length() < second.length()) {
return judgeInsert(first, second);
} else {
return judgeDelete(first, second);
}
}
}