Lintcode ladder F [640. One Edit Distance]

此题属于medium难度!

Description:
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

思路:我刚开始想到的是采用傻子做法,每种情况都给列出来!其实,此题完全可以用用递归处理一部分!
这道题讲的是有俩个字符串,判断是能通过一步的变化使得俩个字符串相等? 可以知道的是字符串长度的大小不能大于1,也不能是俩个字符串相等(坑)不然一步变换不可能相等!
在s长度大于t长度时,设置for循环进行遍历,复制或者插入就可。当t长度大于s长度时,直接用递归就好!

public:
    bool isOneEditDistance(string &s, string &t) 
    {
        int m = s.size();
        int n = t.size();
        if(n - m > 1|| s == t)
        {
            return false;
        }
        if(m > n)
        {
            return isOneEditDistance(t,s);
        }
        for(int i = 0; i < m; i++)
        {
            if(s[i] != t[i])
            {
                if(m == n)
                {
                    s[i] = t[i];
                }
                else
                {
                    s.insert(i,1,t[i]);
                }
                break;
            }
        }
        return s==t || s+t[n-1]==t;
    }
};
posted @ 2020-06-07 00:05  YIJIE珂  阅读(76)  评论(0编辑  收藏  举报