[7 lines C++] Super easy to understand code


  • 0
    H
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            if (s.size() > t.size() + 1 || t.size() > s.size() + 1 || s == t) return false;
            
            int hs = 0, ht = 0;
            while (hs < s.size() && ht < t.size() && s[hs] == t[ht]) { ++hs; ++ht; }
            if (s.size() <= t.size()) ++ht;
            if (t.size() <= s.size()) ++hs;
            
            while (hs < s.size() && ht < t.size() && s[hs] == t[ht]) { ++hs; ++ht; }
            return (hs == s.size() && ht == t.size());
        }
    };
    

Log in to reply
 

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