Simple solution in C++ with one loop in 4 ms


  • 0
    T
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            int m = s.size();
            int n = t.size();
            int i = 0, j = 0;
            int count = 0;
            while (i<m && j<n)
            {
                if (s[i] == t[j])
                {
                    i++,j++;
                }
                else
                {
                    count++;
                    if (count >1) break;
                    if (m -i == n - j)
                        i++,j++;
                    else if (m - i > n - j)
                        i++;
                    else
                        j++;
                }
            }
            if (i!=m || j!=n)
            {
                count+=abs(m-n);
            }
            return count==1;
        }
    };

Log in to reply
 

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