-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path161.java
40 lines (40 loc) · 1004 Bytes
/
161.java
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
33
34
35
36
37
38
39
40
class Solution {
public boolean isOneEditDistance(String s, String t) {
int lengthDiff = Math.abs(s.length() - t.length());
if (lengthDiff > 1 || s.equals(t))
return false;
else if (lengthDiff == 1) {
// check for insert or delete
boolean foundEdit = false;
// make s the longer string
if (t.length() > s.length()) {
String temp = s;
s = t;
t = temp;
}
for (int i = 0, j = 0; j < t.length(); i++, j++) {
if (s.charAt(i) != t.charAt(j)) {
if (foundEdit) {
return false;
} else {
foundEdit = true;
j--;
}
}
}
} else {
// check for replace
boolean foundReplace = false;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != t.charAt(i)) {
if (foundReplace) {
return false;
} else {
foundReplace = true;
}
}
}
}
return true;
}
}