One Edit Distance

LeetCode #161


Description:

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

Example:

Note

Idea:

一些细节需要考虑,不难。

Code:

class Solution {
public:
    bool isOneEditDistance(string s, string t) {
        // One edit distance is easy to solve
        int lenS=s.size(), lenT=t.size();
        if(abs(lenS-lenT)>=2) return false; // cannot be 1 edit
        int flag=lenS-lenT;

        int i=0, j=0;
        while(i<lenS&&j<lenT&&s[i]==t[j]){ // Stop when characters are not equal
            i++;
            j++;
        }
        if(i==lenS&&j==lenT) return false; // means two strings are the same
        else if(i==lenS||j==lenT) return true; // means only one character left

        if(flag==0){ // two strings length are the same, jump over this character
            i++;
            j++;
        }
        else if(flag<0){ // One string is longer, jump over this character in the longer string
            j++;
        }
        else{
            i++;
        }
        while(i<lenS&&j<lenT&&s[i]==t[j]){ // Then continue going
            i++;
            j++;
        }
        if(i==lenS&&j==lenT) // do some checks
            return true;
        else
            return false;

    }
};

results matching ""

    No results matching ""