面试题 01.05. 一次编辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public boolean oneEditAway(String first, String second) {
if (first.length() > second.length()) {
return oneEditAway(second, first);
}

int lengthDiff = second.length() - first.length();
if (lengthDiff > 1) {
return false;
}

int editTimes = 0;
int index1 = 0, index2 = 0;
while (index1 < first.length() && index2 < second.length()) {
if (first.charAt(index1) == second.charAt(index2)) {
index1++;
index2++;
} else {
if (lengthDiff == 0) {
index1++;
index2++;
editTimes++;
} else {
index2++;
editTimes++;
}
}
}

return editTimes <= 1;
}
}

References

面试题 01.05. 一次编辑