Check if edit distance between two strings is one | C ++ program to check if given two strings are at distance one . ; Returns true if edit distance between s1 and s2 is one , else false ; Find lengths of given strings ; If difference between lengths is more than 1 , then strings can 't be at one distance ; int count = 0 ; Count of edits ; If current characters don 't match ; If length of one string is more , then only possible edit is to remove a character ; else Iflengths of both strings is same ; Increment count of edits ; else If current characters match ; If last character is extra in any string ; Driver program
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isEditDistanceOne ( string s1 , string s2 ) { int m = s1 . length ( ) , n = s2 . length ( ) ; if ( abs ( m - n ) > 1 ) return false ; int i = 0 , j = 0 ; while ( i < m && j < n ) { if ( s1 [ i ] != s2 [ j ] ) { if ( count == 1 ) return false ; if ( m > n ) i ++ ; else if ( m < n ) j ++ ; { i ++ ; j ++ ; } count ++ ; } { i ++ ; j ++ ; } } if ( i < m j < n ) count ++ ; return count == 1 ; } int main ( ) { string s1 = " gfg " ; string s2 = " gf " ; isEditDistanceOne ( s1 , s2 ) ? cout << " Yes " : cout << " No " ; return 0 ; }