# 161. One Edit Distance

Given two strings **s** and **t**, determine if they are both one edit distance apart.

**Note:**&#x20;

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.
```

{% hint style="info" %}
這題要找兩個strings的差距是否為一個編輯操作。如果兩個字串完全相等也是false。
{% endhint %}

```cpp
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);
}
```

```cpp
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);
}
```
