3 lines C solution


  • 5

    Skip equal prefixes, then check whether the rests differ but match after skipping another character (in s or t or both, depending on lengths).

    bool isOneEditDistance(char* s, char* t) {
        while (*s == *t && *s) ++s, ++t;
        int d = strlen(s) - strlen(t);
        return *s != *t && !strcmp(s+(d>=0), t+(d<=0));
    }
    

    Slight variation, maybe clearer:

    bool isOneEditDistance(char* s, char* t) {
        while (*s == *t && *s) ++s, ++t;
        int a = strlen(s), b = strlen(t);
        return *s != *t && !strcmp(s+(a>=b), t+(b>=a));
    }

  • 0

    This is too short! Awesome solution!


  • 0
    H

    Hi Stefan, Can I modify the first line to: while (*s == *t ) ++s, ++t;?


  • 0

    @hyelong If you do that and the strings are equal, then you'll read past their end, which is bad.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.