161. One Edit Distance #334
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Resolves: #86
Algorithm:
Firstly, we can do a simple optimization here. If the strings is (1 character) longer than the target, then remove some character from the strings is equivalent to adding a character to the target. In order to only consider adding and replacing, we can call the function again with reversed parameter order if that is the case.
With the operation above, assuming that the target is always longer the string, If target is more than a single character longer than the strings, that means that we cannot get to it in "one edit distance".
Then we iterate through the characters of the string. If 2 characters at the same indices of the string and the target aren't same, that means that this character is either a replacement from the original string, if both string lengths are the same, or a char is added to here in the target.
If the first one is the case, the rest of the two strings have to be same.
If the second one is the case, the rest of the string and the rest of the target starting 1 index after the current position (because of the inserted character) have to be the same. We return those 2 substring checks.
Since the length of the string is shorter than that of the target, we might have gone through all the characters of the string and might not have found any additions, which could be add the end of the target. If so, we can safely return true if the target is longer.