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:

  1. Insert a character into s to get t
  2. Delete a character from s to get t
  3. 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.

解题思路:

这里给我们设定了3种可能的操作:

  1. 替代

  2. 移除

  3. 插入

我们可以根据两个字符串长度的差别来判断可能出现的操作。

然后我们从头到尾一起遍历两个字符串:sIdx遍历s, tIdx遍历t

当我们遇到相同的字符串时,首先判断可能的模式:

  1. 替代:sIdx++, tIdx++

  2.移除:sIdx++

  3.插入:tIdx++

因为我们要求距离为一,代表我们只能进行一次操作,我们可以设置一个bool类型的标识符来标识是否已经进行改动操作。

若进行改动操作后又发现不一样,则代表我们无法只进行一次操作返回false。

当我们结束循环时,若change为true,则可以返回true

注意这里的边界情况,若在最后添加或删除一个字符:"c" "ca",当跳出循环时,change依旧为false,所以我们需要检查长度差。

  1. 若长度差的绝对值为1,则代表在最后插入或删除一个字符,应返回true

  2.若长度差绝对值为0, 则代表两个字符串完全相同,应返回false

代码:

#define REMOVE 0
#define INSERT 1
#define CHANGE 2
class Solution {
public:
    bool isOneEditDistance(string s, string t) {
        int sLen = s.size();
        int tLen = t.size();
        if(sLen == 0){
            if(tLen == 1)
                return true;
            else
                return false;
        }
        if(tLen == 0){
            if(sLen == 1)
                return true;
            else
                return false;
        }
        if(abs(tLen - sLen) > 1)
            return false;
        int changeMode = -1;
        if(tLen - sLen == -1)
            changeMode = REMOVE;
        else if(tLen - sLen == 1)
            changeMode = INSERT;
        else if(tLen == sLen)
            changeMode = CHANGE;
        int sIdx = 0;
        int tIdx = 0;
        bool changed = false;
        while(sIdx < sLen && tIdx < tLen){
            if(s[sIdx] != t[tIdx]){
                if(changed)
                    return false;
                if(changeMode == REMOVE){
                    sIdx++;
                }else if(changeMode == INSERT){
                    tIdx++;
                }else if(changeMode == CHANGE){
                    sIdx++;
                    tIdx++;
                }
                changed = true;
                continue;
            }
            sIdx++;
            tIdx++;
        }
        if(changed)
            return true;
        
        return abs(tLen - sLen);
    }
};

猜你喜欢

转载自www.cnblogs.com/yaoyudadudu/p/9196939.html