3ms Very Straightforward C++ Solution


  • 0
    A

    State 1: s and t have the length. Just sequentially compare each char in two strings. Return false if more than one differences are found.
    State 2: s is one char longer than t. Sequentially compare each char in two strings and only move the cursor of s forward when a difference is found.

        bool isOneEditDistance(string s, string t) {
            int m = s.length(), n = t.length();
            if (m < n) return isOneEditDistance(t, s);
            
            if (s == t) return false;
            if (m <= 1) return true;
            else if (m - n >= 2) return false;
            
            int found = 0;
            if (m == n) {
                for (int i = 0; i < n; ++i)
                    if (s[i] != t[i] && ++found > 1) return false;
                return true;
            }
            for(int i = 0, j = 0; i < m && j < n; ++ i)
                if (s[i] == t[j]) ++j;
                else if (++found > 1) return false;
            return true;
        }
    

Log in to reply
 

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