1.5 - One Away

There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. EXAMPLE pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false

Algorithm:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

bool OneAway(char* str1, char* str2){
    
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    int i = 0, j = 0;
    
    for(i = 0, j = 0; i < len1 && j < len2; i++, j++){
        if(str1[i] != str2[j]){
            break;
        }
    }
    
    if( i == len1 && j == len2){
        return true;
    }

    int e_i = len1 - 1, e_j = len2 -1;
    for(e_i = len1 - 1, e_j = len2 -1; e_i >= i && e_j >= j; e_i--, e_j--){
        if(str1[e_i] != str2[e_j]){
            break;
        }
    }
    
    printf("i = %d, j = %d, ei = %d, ej = %d\n", i, j, e_i, e_j);
    
    return (e_i - i <= 1) && (e_j - j <= 1);
}

Test:

int main(){


    char testStr1[100] = "pale";
    char testStr2[100] = "ple";
    printf("OneAway = %d\n", OneAway(testStr1, testStr2));

    return 0;
}

Last updated