- One Edit Distance
Given two strings S and T, determine if they are both one edit distance apart.
One ediit distance means doing one of these operation:
insert one character in any position of S
delete one character in S
change one character in S to other character
Example
Example 1:
Input: s = “aDb”, t = “adb”
Output: true
Example 2:
Input: s = “ab”, t = “ab”
Output: false
Explanation:
s=t ,so they aren’t one edit distance apart
解法1:
分3种情况考虑:
- 两个字符串长度之差大于1,返回false。
- 两个字符串长度之差等于1,长的那个字符串去掉一个字符,剩下的应该和短的字符串相同。
- 两个字符串长度相同,两个字符串对应位置的字符只能有一处不同。
class Solution {
public:
/**
* @param s: a string
* @param t: a string
* @return: true if they are both one edit distance apart or false
*/
bool isOneEditDistance(string &s, string &t) {
string shortStr, longStr;
if (s.size() <= t.size()) {
shortStr = s;
longStr = t;
} else {
shortStr = t;
longStr = s;
}
int m = shortStr.size();
int n = longStr.size();
if (shortStr == longStr) return false;
if (m < n - 1) return false;
if (m == n) {
int numOfDiff = 0;
for (int i = 0; i < m; ++i) {
if (shortStr[i] != longStr[i]) {
numOfDiff++;
if (numOfDiff > 1) return false;
}
}
return numOfDiff == 1;
}
if (m == n - 1) {
for (int i = 0; i < m; ++i) { //up to shortStr.size()
if (shortStr[i] != longStr[i]) return longStr.substr(i + 1) == shortStr.substr(i);
}
return true;
}
}
};
解法2:很简洁。
参考https://www.cnblogs.com/grandyang/p/5184698.html
class Solution {
public:
/**
* @param s: a string
* @param t: a string
* @return: true if they are both one edit distance apart or false
*/
bool isOneEditDistance(string &s, string &t) {
for (int i = 0; i < min(s.size(), t.size()); ++i) {
if (s[i] != t[i]) {
if (s.size() == t.size()) return s.substr(i + 1) == t.substr(i + 1);
if (s.size() == t.size() + 1) return s.substr(i + 1) == t.substr(i);
if (t.size() == s.size() + 1) return t.substr(i + 1) == s.substr(i);
}
}
return abs((int)s.size() - (int)t.size()) == 1;
}
};
三刷:
class Solution {
public:
/**
* @param s: a string
* @param t: a string
* @return: true if they are both one edit distance apart or false
*/
bool isOneEditDistance(string &s, string &t) {
if (s == t) return false;
int n1 = s.size(), n2 = t.size();
if (abs(n1 - n2) > 1) return false;
int pos = 0;
while (pos < n1 && pos < n2) {
if (s[pos] != t[pos]) break;
pos++;
}
if (pos < n1 && pos < n2) return s.substr(pos + 1) == t.substr(pos + 1) ||
s.substr(pos) == t.substr(pos + 1) ||
s.substr(pos + 1) == t.substr(pos);
if (pos >= n1) return t.substr(0, n1) == s;
if (pos >= n2) return s.substr(0, n2) == t;
return false;
}
};