-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathOneEditDistance.java
More file actions
54 lines (51 loc) · 1.15 KB
/
Copy pathOneEditDistance.java
File metadata and controls
54 lines (51 loc) · 1.15 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package leetcode;
import java.util.Arrays;
//Given two strings S and T, determine if they are both one edit distance apart
public class OneEditDistance {
public boolean isOneEditDistance(String s,String t){
int slength = s.length();
int tlength = t.length();
int diff = Math.abs(tlength-slength);
if(diff >= 2)
return false;
int sp = 0;
int tp = 0;
while(sp < slength && tp < tlength)
{
if(s.charAt(sp) != t.charAt(tp)){
if(diff == 0){
sp++;
tp++;
diff--;
}
else if(diff == 1){
if(slength < tlength){
diff = -1;
sp++;
} // delete on character
else if(tlength < slength){
diff = -1;
tp++;
}
}
else{
return false;
}
}
else{
sp++;
tp++;
}
}
if(slength == tlength)
return diff==-1;
else if(slength > tlength)
return (diff==-1 && sp == slength && tp == tlength) || (diff==1 && sp< slength);
else
return (diff==-1 && sp == slength && tp == tlength) || (diff==1 && tp< tlength);
}
public static void main(String[] args) {
OneEditDistance oed = new OneEditDistance();
System.out.println(oed.isOneEditDistance("a", "ba"));
}
}