C++ without explicit loops


  • 0
    M

    std::mismatch() finds the first point at which two sequences differ. std::string::compare() has overloads that allow offsets into strings being compared.

        bool isOneEditDistance(string s, string t)
        {
            // Let s be shortest
            if (s.size() > t.size()) swap(s, t);
    
            auto M = s.size();
            auto N = t.size();
    
            if (M + 1 < N) return false;
    
            bool okay = false;
    
            // look for two characters that differ
            auto iter = mismatch(begin(s), end(s), begin(t));
            if (iter.second != end(t))
            {
                // compare tails for equality, with allowances for M == N
                auto off = distance(begin(s), iter.first) + (M == N);
                okay = s.compare(off, N - off, t, off + (M < N), N - off) == 0;
            }
    
            return okay;
        }
    

Log in to reply
 

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