# 161.One Edit Distance

[Link](https://medium.com/leetcode-%E6%BC%94%E7%AE%97%E6%B3%95%E6%95%99%E5%AD%B8/020-leetcode-161-%E6%BC%94%E7%AE%97%E6%B3%95-one-edit-distance-%E7%B7%A8%E8%BC%AF%E8%B7%9D%E9%9B%A2-d44915b9112b)

Given two strings S and T, determine if they are both one edit distance apart.

**Example 1:**

```
Input: s = "aDb", t = "adb" 
Output: true
```

**Example 2:**

```
Input: s = "ab", t = "ab" 
Output: false
Explanation:
s=t ,so they aren't one edit distance apart
```

**Example 3:**

```
Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.
```

**Solution**

當char\[i] != char\[j]時只會三種狀況讓editdistance是1

1. abd, bd&#x20;

```
s.substring(i + 1).equals(t.substring(j))
```

&#x20;  2\. ad, cad&#x20;

```
s.substring(i).equals(t.substring(j + 1))
```

&#x20;3\. acd, ecd

```
s.substring(i+1).equals(t.substring(j + 1))
```

```
public boolean isOneEditDistance(String s, String t) {
    if(s==null || t==null)
        return false;
 
    int m = s.length();
    int n = t.length();
 
    if(Math.abs(m-n)>1){
        return false;
    }
 
    int i=0; 
    int j=0; 
    int count=0;
 
    while(i<m&&j<n){
        if(s.charAt(i)==t.charAt(j)){
            i++;
            j++;
        }else{
            count++;
            if(count>1)
                return false;
 
            if(m>n){
                i++;
            }else if(m<n){
                j++;
            }else{
                i++;
                j++;
            }
        }
    }
 
    if(i<m||j<n){
        count++;
    }
 
    if(count==1)
        return true;
 
    return false;
}
```
