Leetcode-161.One Edit Distance

来源:互联网 发布:xp系统网络共享密码 编辑:程序博客网 时间:2024/06/05 06:49

Problem Description:
Given two strings S and T, determine if they are both one edit distance apart.

Analysis:
Ref: http://www.cnblogs.com/jcliBlogger/p/4602455.html
For the one edit distance, you can check the wiki link here :
https://en.wikipedia.org/wiki/Edit_distance
Actually, you only can
1) Insert a character
2) Delete a character
3) Replace a character
For cases 1 and 2, S and T will be one apart in their lengths. For cases 3, they are of the same length.
In fact, cases 1, 2 and 3 can be further handled using the same piece of code. For strings of the same length, once we find a mismatch, we just substitute one to be another and check whether they are now the same. For strings of one apart in lengths, we insert the deleted character of the long string into the short one and compare whether they are the same.
For example, Assume that, S is “leetcode”, T is “leecode”,
we compare two string from scratch, for the 4th char, ‘t’ is not equal with ‘c’, so we insert the ‘t’ in T, then comparing whether S is same with T.
also the boundary case: “abc”,”bc”,”ab”;
Updated code:

 bool isOneEditDistance(string s, string t) {        int m = s.size(), n = t.size();        if (m > n) return isOneEditDistance(t, s);        if (n - m > 1)return false;//         for (int i = 0; i < m; ++i)        {            if (s[i] != t[i]){                if (m == n)                      {   //cout<<s.substr(i) << " "<<t.substr(i);                        return s.substr(i + 1) == t.substr(i + 1);//compare new substr from index i + 1                     }                else                 {                s.insert(i, 1, t[i]);                return s == t;                 }                            }        }        return !(m == n);//case : "ba", "ba"    }
#include <iostream>using namespace std;class Solution {public:    bool isOneEditDistance(string s, string t) {        int m = s.size(), n = t.size();        if (abs(m - n) > 1) return false;        if ( m > n) return isOneEditDistance(t, s);        bool flag = false;        for (int i = 0, j = 0; i < m; ++i, ++j)        {            if (s[i] != t[j])            {                if (m == n) s[i] = t[j];                else s.insert(i, 1, t[j]);                flag = true;                break;            }        }        return ((!flag && (n - m == 1))|| (flag && s == t));    }};int main(int argc, char const *argv[]){    Solution s;    cout<<s.isOneEditDistance("bcb","bca");    return 0;}
0 0
原创粉丝点击