Interview questions. One edit

There are three editing operations for strings: insert an English character, delete an English character, or replace an English character. Given two strings, write a function to determine whether they require only one (or zero) edits.

Example 1:

enter:
first = "pale"
second = "ple"
Output: True

Example 2:

enter:
first = "pales"
second = "pal"
Output: False

code show as below:

//只进行一次编辑有三种情况
//1.替换,两个字符串的长度相等,但其中有一个字符不相等
//2.插入,first<second,并且只有一个字符不一样
//3.删除,first>second,并且只有一个字符不一样
class Solution {
public:
    bool oneEditAway(string first, string second) {
        int m=first.size();
        int n=second.size();
        if(n-m>1||m-n>1)
        {
            return false;//两个字符串的长度相差大于1,不只进行一次操作
        }
        if(n==m+1)
        {
            return oneEditAway(second,first);//插入-->与删除刚好相反
        }
        int i=0,j=0;
        int count=0;
        while(i<m&&j<n)
        {
            if(first[i]!=second[j])
            {
                count++;
                if(count>=2)
                {
                    return false;
                }
                if(m>n)//删除
                {
                    j--;//为了让原地等待,先回退一步,后面会在向右移一步
                }
            }
            i++;//每次向右移一步
            j++;//每次向左移一步

        }
        return true;

    }
};

Guess you like

Origin blog.csdn.net/m0_62379712/article/details/132250757