#### 暴力求解

``````class Solution {
public:
bool oneEditAway(string first, string second) {
int m = first.size(),n = second.size();
//相等返回true
if(first == second) return true;

//长度相差大于1
if(abs(m - n) > 1) return false;

//长度相等,只能有一个不相同
if(m == n)
{
if(m == 1) return true;
int cnt = 0;
for(int i = 0;i < m ;i++)
{
if(first[i] != second[i])
{
if(++cnt > 1) return false;
}
}
return true;
}

if(abs(m - n ) == 1){
if(first.find(second) != std::string::npos ||
second.find(first) !=std::string::npos) {
return true;
}else {
return false;
}
}

return false;
}
};``````

``````1145 / 1146 个通过测试用例

"teacher"
"treacher"

#### 双指针解法

``````class Solution {
public:
bool oneEditAway(string first, string second) {
//相等返回true
if(first == second) return true;

//长度相差大于1,返回false
int m = first.size(),n = second.size();
if(abs(m - n) > 1) return false;
//长度相差小于等于1
int l = 0,r1 = m -1,r2 = n - 1;
while(l <= r1 && l <= r2 && first[l] == second[l]) l++;
while(r1 >= 0 && r2 >= 0 && first[r1] == second[r2]) {r1--;r2--;}
if(r1-l < 1 && r2-l < 1) return true;

return false;
}
};``````

``````执行结果：通过

#### 动态规划

dp[i+1][j+1]表示A的前i个字符与B的前j个字符，如果要通过替换 插入 删除变成一致最少需要的步数时多少?

A[i]后面插入B[j]:dp[i+1][j+1] =dp[i+1][j] + 1;在原来A[i]后面插入B[j]，dp[i+1][j+1] = dp[i+1][j] + 1.

``````class Solution {
public:
bool oneEditAway(string first, string second) {
int m = first.size(),n = second.size();
int dp[m+1][n+1];
dp[0][0] = 0;

//其中一个字符串为空时,更新最小操作次数
for(int i = 1;i <= m;i++) dp[i][0] = i;
for(int i = 1;i <= n;i++) dp[0][i] = i;

for(int i = 0;i < m;i++)
{
for(int j = 0;j < n;j++)
{
if(first[i] == second[j])
dp[i+1][j+1] = dp[i][j];
else
dp[i+1][j+1] = min(min(dp[i][j],dp[i+1][j]),dp[i][j+1]) + 1;
}
}
if(dp[m][n] <= 1) return true;
return false;
}
};``````