Given two strings S and T, determine if they are both one edit distance apart.

Two pointer O(n) time O(1) space solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Solution {
public boolean isOneEditDistance(String s, String t) {
if (s == null || t == null) {
return false;
}
int length = Math.min(s.length(), t.length());
for (int i = 0; i < length; i++) {
if (s.charAt(i) != t.charAt(i)) {
if (s.length() == t.length()) {
//abc, adc
return s.substring(i + 1).equals(t.substring(i + 1));
} else if (s.length() > t.length()) {
// abcd, acd
return t.substring(i).equals(s.substring(i + 1));
} else {
// acd, abcd
return s.substring(i).equals(t.substring(i + 1));
}
}
}
// abc, abcde
return Math.abs(s.length() - t.length()) == 1;
}
}