161. One Edit Distance
Given two strings s and t, determine if they are both one edit distance apart.
Note:
There are 3 possiblities to satisify one edit distance apart:
Insert a character into s to get t
Delete a character from s to get t
Replace a character of s to get t
Example 1:
Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.
Example 2:
Input: s = "cab", t = "ad"
Output: false
Explanation: We cannot get t from s by only one step.
Example 3:
Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.
bool isOneEditDistance(string s, string t) { // time: O(min(m, n)); space: O(1)
if (s.empty() && t.empty()) return false;
int m = s.size(), n = t.size();
for (int i = 0; i < min(m, n); ++i) {
if (s[i] != t[i]) {
if (m == n)
return s.substr(i + 1).compare(t.substr(i + 1)) == 0;
else
return (m > n) ? s.substr(i + 1).compare(t.substr(i)) == 0 : s.substr(i).compare(t.substr(i + 1)) == 0;
}
}
return (m < n && m + 1 == n) || (m > n && m == n + 1);
}
bool isOneEditDistance(string s, string t) { // time: O(min(m, n)); space: O(1)
if (s.empty() && t.empty()) return false;
int m = s.length(), n = t.length();
if (abs(m - n) > 1) return false;
for (int i = 0; i < min(m, n); ++i) {
if (s[i] == t[i]) continue;
if (m == n)
return s.substr(i + 1) == t.substr(i + 1);
else
return (m > n) ? s.substr(i + 1) == t.substr(i) : s.substr(i) == t.substr(i + 1);
}
return (m > n && m == n + 1) || (m < n && m + 1 == n);
}
Last updated
Was this helpful?