161. One Edit Distance - CPP - Solution


  • 0
    Y
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            bool result = false;
            if (s.size() > t.size()) {
                result = isOneEditDistance(t, s);
            }
            else if (s.size() <= t.size()) {
                size_t i = 0;
                for(i = 0; i < s.size(); ++i) {
                    if (s[i] != t[i]) {
                        break;
                    }
                }
                if (!result && s.size() == t.size()) {
                    if (!result && i < s.size()) {
                        string sCopy(s);
                        sCopy[i] = t[i];
                        result = result || sCopy == t;                    
                    }
                    // if (!result && i + 1 < s.size()) {
                    //     string sCopy(s);
                    //     swap(sCopy[i], sCopy[i + 1]);
                    //     result = result || sCopy == t;
                    // }
                }
                else if (!result && s.size() + 1 == t.size()) {
                    string sCopy(s);
                    sCopy.insert(i + sCopy.begin(), t[i]);
                    result = result || sCopy == t;
                }
            }
            return result;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.