Skip to content

Commit c81691f

Browse files
authored
Update One Edit Distance.java
1 parent effd03f commit c81691f

File tree

1 file changed

+34
-45
lines changed

1 file changed

+34
-45
lines changed

Medium/One Edit Distance.java

Lines changed: 34 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,39 @@
11
class Solution {
2-
public static boolean isOneEditDistance(String s, String t) {
3-
if (Math.abs(s.length() - t.length()) > 1) {
4-
return false;
5-
}
6-
else if (s.length() - t.length() == 0) {
7-
if (s.equals(t)) {
8-
return false;
9-
}
10-
11-
boolean missed = false;
12-
for (int i=0; i<s.length(); i++) {
13-
if (s.charAt(i) == t.charAt(i)) {
14-
continue;
15-
}
16-
if (missed) {
17-
return false;
18-
}
19-
20-
missed = true;
21-
}
22-
return true;
23-
}
24-
25-
return s.length() - t.length() == 1 ? oneDeleteOnly(s,t) : oneDeleteOnly(t,s);
2+
public boolean isOneEditDistance(String s, String t) {
3+
int lengthDiff = Math.abs(s.length() - t.length());
4+
if (s.equals(t) || lengthDiff > 1) {
5+
return false;
266
}
27-
28-
private static boolean oneDeleteOnly(String s, String t) {
29-
if (t.length() == 0) {
30-
return true;
31-
}
32-
int i = 0;
33-
int j = 0;
34-
35-
while (i < s.length() && j < t.length()) {
36-
if (s.charAt(i) != t.charAt(j)) {
37-
if (i > j) {
38-
return false;
39-
}
40-
i++;
41-
continue;
42-
}
43-
44-
i++;
45-
j++;
7+
if (s.length() == 0 || t.length() == 0) {
8+
return true;
9+
}
10+
int idxOne = 0;
11+
int idxTwo = 0;
12+
boolean changeDone = false;
13+
while (idxOne < s.length() && idxTwo < t.length()) {
14+
if (s.charAt(idxOne) == t.charAt(idxTwo)) {
15+
idxOne++;
16+
idxTwo++;
17+
continue;
18+
}
19+
if (changeDone) {
20+
return false;
21+
}
22+
if (lengthDiff != 0) {
23+
if (s.length() > t.length()) {
24+
idxOne++;
25+
} else {
26+
idxTwo++;
4627
}
47-
48-
return true;
28+
} else {
29+
idxOne++;
30+
idxTwo++;
31+
}
32+
changeDone = true;
33+
}
34+
if (changeDone && (idxOne != s.length() || idxTwo != t.length())) {
35+
return false;
4936
}
37+
return true;
38+
}
5039
}

0 commit comments

Comments
 (0)