# One Edit Distance in C++

Suppose we have two strings s and t; we have to check whether they are both one edit distance apart. The one edit distance has three types −

• Insert a character into s to get t

• Delete a character from s to get t

• Replace a character of s to get t

So, if the input is like s = "ab", t = "acb", then the output will be True

To solve this, we will follow these steps −

• n := size of s, m := size of t

• if n < m, then −

• return isOneEditDistance(t, s)

• for initialize i := 0, when i < m, update (increase i by 1), do −

• if s[i] is not equal to t[i], then −

• if n is same as m, then −

• return true when substring of s from index 0 to (i) is the same as the substring of t from index 0 to (i)

• return true when substring of s from index 0 to (i) is the same as the substring of t from index 0 to (i - 1)

• return true when m + 1 is the same as n

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isOneEditDistance(string s, string t) {
int n = s.size();
int m = t.size();
if (n < m) {
return isOneEditDistance(t, s);
}
for (int i = 0; i < m; i++) {
if (s[i] != t[i]) {
if (n == m) {
return s.substr(i + 1) == t.substr(i + 1);
}
return s.substr(i + 1) == t.substr(i);
}
}
return m + 1 == n;
}
};
main(){
Solution ob;
cout << (ob.isOneEditDistance("ab", "acb"));
}

## Input

s = "ab", t = "acb"

## Output

1

Updated on: 18-Nov-2020

81 Views