-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy path640.edit-distance-ii.java
More file actions
54 lines (46 loc) · 1.46 KB
/
640.edit-distance-ii.java
File metadata and controls
54 lines (46 loc) · 1.46 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
public class Solution {
/*
* @param s: a string
* @param t: a string
* @return: true if they are both one edit distance apart or false
*/
public boolean isOneEditDistance(String s, String t) {
if (s == null || t == null) {
return false;
}
// Assume s is the shorter one.
if (s.length() > t.length()) {
return isOneEditDistance(t, s);
}
// One edit distance can be:
// - add a char
// - remove a char
// - replace a char
// not one edit distance
if (t.length() - s.length() > 1) {
return false;
}
// same length, only one char can be replaced
char[] sc = s.toCharArray();
char[] tc = t.toCharArray();
if (s.length() == t.length()) {
int count = 0;
for (int i = 0; i < sc.length; i++) {
if (sc[i] != tc[i]) {
count++;
}
}
return count == 1;
}
// different length. Either add a char, or remove a char.
if (s.length() < t.length()) {
// find the first idx that are different
for (int i = 0; i < sc.length; i++) {
if (sc[i] != tc[i]) {
return s.substring(i).equals(t.substring(i+1));
}
}
}
return true;
}
}