# 161. One-Edit-Distance

difficulty: Medium

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:**

<pre><code><strong>Input: s = "ab", t = "acb"
</strong><strong>Output: true
</strong><strong>Explanation: We can insert 'c' into s to get t.
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: s = "cab", t = "ad"
</strong><strong>Output: false
</strong><strong>Explanation: We cannot get t from s by only one step.
</strong></code></pre>

**Example 3:**

<pre><code><strong>Input: s = "1203", t = "1213"
</strong><strong>Output: true
</strong><strong>Explanation: We can replace '0' with '1' to get t.
</strong></code></pre>

## Method One

```Java
class Solution {
    public boolean isOneEditDistance(String s, String t) {
        int m = s.length();
        int n = t.length();
        if( n < m ) {
            return isOneEditDistance(t, s);
        }
        // 设定 m <= n;
        // 如果长度差大于 1, 无解
        if( n - m > 1) {
            return false;
        }
        
        //至多有一个位置不一样。
        // 举例子, 两种情况，第一种长度相等。
        // abbb
        // acbb 
        // 如果某位不同，那么直接比较后面的子字符串
        // 第二种长度只差一位
        // abbb
        // acbbb
        // 如果某位不同，那么我们看看去掉长的字符串的这位之后，两个子数组是否还一致
        for(int i = 0; i < m; i++ ) {
            if ( s.charAt(i) == t.charAt(i) ) {
                continue;
            }
            if( n == m ) {
                return s.substring(i + 1, m).compareTo( t.substring( i + 1, n) ) == 0;
            }else{
                return s.substring(i, m).compareTo( t.substring(i + 1, n) ) == 0;
            }
        }
        return !(m == n);    // 排除两者完全相等的情况。
        
    }
}
​
```
