Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 6cc7efc

Browse files
MEDIUM/src/medium/OneEditDistance.java
1 parent 29e3537 commit 6cc7efc

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package medium;
2+
3+
public class OneEditDistance {
4+
5+
public static boolean isOneEditDistance(String s, String t) {
6+
char[] schar = s.toCharArray();
7+
char[] tchar = t.toCharArray();
8+
9+
if(Math.abs(s.length() - t.length()) == 1){
10+
char[] longer = (s.length() > t.length()) ? schar : tchar;
11+
char[] shorter = (longer == schar) ? tchar : schar;
12+
13+
int diffCnt = 0, i = 0, j = 0;
14+
for(; i < shorter.length && j < longer.length;){
15+
if(longer[j] != shorter[i]){
16+
diffCnt++;
17+
j++;
18+
} else {
19+
i++;
20+
j++;
21+
}
22+
}
23+
return diffCnt == 1 || diffCnt == 0;//it could be the last char of the longer is the different one, in that case, diffCnt remains to be zero
24+
} else if(s.length() == t.length()) {
25+
int diffCnt = 0;
26+
for(int i = 0; i < s.length(); i++){
27+
if(schar[i] != tchar[i]) {
28+
diffCnt++;
29+
}
30+
if(diffCnt > 1) return false;
31+
}
32+
return diffCnt == 1;
33+
}
34+
return false;
35+
}
36+
37+
public static void main(String...strings){
38+
String s = "a";
39+
String t = "ac";
40+
System.out.println(isOneEditDistance(s, t));
41+
}
42+
43+
}

0 commit comments

Comments
 (0)