forked from chihungyu1116/leetcode-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path161 One Edit Distance.js
81 lines (60 loc) · 1.35 KB
/
161 One Edit Distance.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Given two strings S and T, determine if they are both one edit distance apart.
// Hide Company Tags Snapchat Uber Facebook Twitter
// Hide Tags String
// Hide Similar Problems (H) Edit Distance
/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/
// tricky question!
var isOneEditDistance = function(s, t) {
if(s.length > t.length) {
var tmp = s;
s = t;
t = tmp;
}
if((t.length - s.length) > 1) {
return false;
}
var found = false;
for(var i = 0, j = 0; i < s.length; i++, j++) {
if(s[i] !== t[j]) {
if(found) {
return false;
}
found = true;
if(s.length < t.length) {
i--;
}
}
}
return found || s.length < t.length;
};
var isOneEditDistance = function(s, t) {
if(s.length > t.length) {
var tmp = s;
s = t;
t = tmp;
}
if(t.length - s.length > 1) {
return false;
}
var i = 0;
var j = 0;
var diff = 0;
while(i < s.length && j < t.length) {
if(s[i] !== t[j]) {
if(diff !== 0) {
return false;
}
diff++;
if(t.length !== s.length) {
i--;
}
}
i++;
j++;
}
return diff === 1 || (t.length !== s.length && (t.length - j) === 1);
};