Idea from prefix and suffix


  • 1
    A
    1. find common prefix and suffix length
    2. determine (prefix+suffix+1) == max(s.size(),t.size())
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            int prefix = 0, suffix = 0;
            
            int i = 0, j;
            while (i < s.size() && i < t.size() && s[i]==t[i]) {
                prefix++;
                i++;
            }
            
            i = s.size()-1;
            j = t.size()-1;
            while (i >= prefix && j >= prefix && s[i]==t[j]) {
                suffix++;
                i--, j--;
            }
            
            return (prefix+suffix+1) == max(s.size(),t.size());
        }
    };
    

Log in to reply
 

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