Skip to content

Latest commit

 

History

History

161

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

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:

  1. Insert a character into s to get t
  2. Delete a character from s to get t
  3. 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.

Companies:
Facebook, Uber, Google

Related Topics:
String

Similar Questions:

Solution 1.

Reuse the solution of Edit Distance

// OJ: https://leetcode.com/problems/one-edit-distance/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(min(M,N))
class Solution {
private:
    int editDistance(string &s, string &t) {
        if (s.size() < t.size()) swap(s, t);
        int M = s.size(), N = t.size();
        vector<int> dp(N + 1, 0);
        for (int i = 1; i <= N; ++i) dp[i] = i;
        for (int i = 1; i <= M; ++i) {
            int pre = dp[0];
            dp[0] = i;
            for (int j = 1; j <= N; ++j) {
                int tmp = dp[j];
                if (s[i - 1] == t[j - 1]) dp[j] = pre;
                else dp[j] = min(pre, min(dp[j - 1], dp[j])) + 1;
                pre = tmp;
            }
        }
        return dp[N];
    }
public:
    bool isOneEditDistance(string s, string t) {
        return editDistance(s, t) == 1;
    }
};

Solution 2.

// OJ: https://leetcode.com/problems/one-edit-distance/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(1)
class Solution {
public:
    bool isOneEditDistance(string s, string t) {
        if (s.size() < t.size()) swap(s, t);
        if (s.size() - t.size() > 1) return false;
        int i = 0;
        while (i < t.size() && s[i] == t[i]) ++i;
        return s.size() > t.size() ? !s.compare(i + 1, string::npos, t, i)
                : (i != t.size() && !s.compare(i + 1, string::npos, t, i + 1));
    }
};