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
s
to gett
- Delete a character from
s
to gett
- Replace a character of
s
to gett
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Explanation 1
-
First, we make
s
to be the longer length string by comparings.size()
andt.size()
, ifs.size()
is smaller, we swaps
andt
. -
We calculate the
diff = s.size() - t.size()
. If thediff
is greater than or equal to 2, then we immediatly returnfalse
. -
Else if the
diff
is equal to 1, then we loopi
throught
from 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 loopi
throught
from 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
i
from 0 tomin(s.size(), t.size())
exclusive. -
If the current index’s character is different, then we check if
s
has longer length, then we want to removes[i]
, so we returns.substr(i + 1) == t.substr(i)
. -
Else if
t
has 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 |
|