161. One Edit Distance
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 get t
Delete a character from s to get t
Replace a character of s to get t
Example 1:
Input: s = "ab", t = "acb"
Output: true
Explanation: We can insert 'c' into s to get t.
Example 2:
Input: s = "cab", t = "ad"
Output: false
Explanation: We cannot get t from s by only one step.
Example 3:
Input: s = "1203", t = "1213"
Output: true
Explanation: We can replace '0' with '1' to get t.
方法1:
思路:
心力交瘁。上来之后没有想到这几个trick:1. 将s.size(), t.size()先确定好,2. 用swap掌握较大的是s还是t,之后跳过的时候判断很简便,3. 如果长度大于2可以直接false,3. 较大的string跳过一个之后不用继续遍历,再用count来判断剩下的是否一致,直接用substr截取后面所有,一样就true不一样就false。4. 对于相等的情况,为什么我们不用上面substr的方法直接跳过第一个不一样的数呢?因为还有可能两个字符串完全相等,用count == 1 直接可以排除这种情况,否则就先特判一下是否相等也可以。第二种就是小修改。
易错点
// 只剩下两种情况需要排除
// 1,前面全相等但是后面size相差>1
// 2. 完全相等
// 3. “a” 和 “”的case:循环并没有进入
Complexity
Time complexity: O(n)
Space complexity: O(1)
这个方法是目前最简洁易懂的,没有先判断大小的trick,也可以再简化一点,主要是利用跳过一次以后应该相等的方法。
只需要在最后做两种特判:
class Solution {
public:
bool isOneEditDistance(string s, string t) {
for (int i = 0; i < s.size() && i < t.size(); i++){
if (s[i] == t[i]) continue;
else {
if (s.size() > t.size()) {
return s.substr(i + 1) == t.substr(i);
}
else if (s.size() < t.size()) {
return s.substr(i) == t.substr(i + 1);
}
else {
return s.substr(i + 1) == t.substr(i + 1);
}
}
}
// 只剩下两种情况需要排除
// 1,前面全相等但是后面size相差>1
// 2. 完全相等
return abs((int)s.size() - (int)t.size()) == 1;
}
};
class Solution {
public:
bool isOneEditDistance(string s, string t) {
// 较大的排在s里面
if (s.size() < t.size()) swap(s, t);
int m = s.size();
int n = t.size();
if (m - n >= 2 ) return false;
if (m - n == 1){
for (int i = 0; i < s.size(); i++){
if (s[i] != t[i]{
return s.substr(i + 1) == t.substr(i);
}
return true;
}
else{
int count = 0;
for (int i = 0; i < s.size(); i++){
if (s[i] != t[i]) {
count ++;
}
}
return count == 1;
}
}
};
相等时的判断稍作修改:
class Solution {
public:
bool isOneEditDistance(string s, string t) {
// 较大的排在s里面
if (s.size() < t.size()) swap(s, t);
int m = s.size();
int n = t.size();
if (m - n >= 2 ) return false;
if (m - n == 1){
for (int i = 0; i < s.size(); i++){
if (s[i] != t[i]){
return s.substr(i + 1) == t.substr(i);
}
}
return true;
}
else{
if (s == t) return false;
for (int i = 0; i < s.size(); i++){
if (s[i] != t[i]) {
return s.substr(i + 1) == t.substr(i + 1);
}
}
return false;
}
}
};