161. One Edit Distance

  • Difficulty: Medium

  • Topics: String

  • Similar Questions:

Problem:

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.

Solutions:

class Solution {
public:
    bool isOneEditDistance(string s, string t) {
        if (s.length() == t.length()) {
            return isOneReplace(s, t);
        } else {
            if (s.length() - t.length() == 1) {
                return isOneDelete(s, t);
            } else if (t.length() - s.length() == 1) {
                return isOneDelete(t, s);
            } else {
                return false;
            }
        }
    }

    bool isOneReplace(string& s, string& t) {
        int diff = 0;
        for (int i = 0; i < s.length(); ++i) {
            if (s[i] != t[i]) {
                if (++diff > 1) return false;
            }
        }

        return diff == 1;
    }

    bool isOneDelete(string& s, string& t) {
        int i = 0;
        while (i < t.length() && s[i] == t[i]) ++i;
        if (i == t.length())    return true;

        while (i < t.length() && s[i+1] == t[i]) ++i;
        return i == t.length();
    }
};

results matching ""

    No results matching ""