Problem
Given two strings s and t, determine if they are both one edit distance apart.
Note:
There are 3 possiblities to satisify one edit distance apart:
- Insert a character into
sto gett - Delete a character from
sto gett - Replace a character of
sto gett
Example 1:
1 | |
Example 2:
1 | |
Example 3:
1 | |
Explanation 1
-
First, we make
sto be the longer length string by comparings.size()andt.size(), ifs.size()is smaller, we swapsandt. -
We calculate the
diff = s.size() - t.size(). If thediffis greater than or equal to 2, then we immediatly returnfalse. -
Else if the
diffis equal to 1, then we loopithroughtfrom index 0 tot.size()exclusive. Ifs[i] != t[i], then we want to removes[i], in other words, we return ` s.substr(i + 1) == t.substr(i)`. -
Else the
diff == 0, then we loopithroughtfrom index 0 tot.size()exclusive, and count how many characters are different, and returncnt == 1.
Solution 1
1 | |
Explanation 2
-
We can simplify the above code. First we loop through
ifrom 0 tomin(s.size(), t.size())exclusive. -
If the current index’s character is different, then we check if
shas longer length, then we want to removes[i], so we returns.substr(i + 1) == t.substr(i). -
Else if
thas longer length, then we want to removet[i], so we returns.substr(i) == t.substr(i + 1). -
Else if they are the same length, then we remove both
s[i]andt[i], in other words, returns.substr(i + 1) == t.substr(i + 1). -
Outside the for loop, if the first
min(s.size(), t.size())characters are the same, thens.size()andt.size()must difference by 1, in other words, we returnabs((int)s.size() - (int)t.size()) == 1.
Solution 2
1 | |