4 ms·
Many of these sorts of problems seem intimidating at first, but if you’ve had any training / exposure to implementing recursive solutions (i.e. a bit of SICP),
by cellularmitosis 7y ago
Many of these sorts of problems seem intimidating at first, but if you’ve had any training / exposure to implementing recursive solutions (i.e. a bit of SICP), the solutions come much easier because you are trained to think in terms of “what is the tiniest amount of work I can do to advance the problem by one step?”
In this case, all we need at each step is to look at one character plus one lookahead character from each string. We’ll call them a and b for string 1 and c and d for string 2.
If a and c are equal, advance.
If a and d are equal, delete c and advance.
If b and c are equal, delete a and advance.
If b and d are equal, change one of a or c so they match, then advance.
Once you use up an edit, the algo changes to “a and c must match” for the rest of the string.
Edit: terminate the algo when one of a or c is a NULL char. If they are both NULL, the string passes. If only one is NULL, then your one edit allowance was not enough to make the strings equal.
Also, rather than “deleting” a char, it is sufficient to simply advance that pointer an extra step.