3ms C++ Code


  • 0
    T
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            //two occasions
            int size_s = s.size();
            int size_t = t.size();
            //Special cases
            if( size_t == 0 && size_s == 0)
                return false;
            if( size_t == 0 && size_s == 1 || size_t == 1 && size_s == 0)
                return true;
            if( size_t == 0 || size_s == 0)
                return false;
                
            if(size_s == size_t)
                return changeHelper(s, t, size_t);
            else if(abs(size_s - size_t) == 1)
                return addHelper(s, t, size_s, size_t);
            else
                return false;
        }
        bool changeHelper(string s, string t, int size){
            int count = 0;
            for(int i = 0; i < size; i++)
            {
                if(s[i] != t[i])
                    count++;
            }
            return count == 1;
        }
        bool addHelper(string s, string t, int size_s, int size_t){
            if(size_s > size_t)
                return addHelper(t, s, size_t, size_s);
            int start = 0;
            //find the position of differnent character
            while(s[start] == t[start])
               start++;
            int pos_s = start;
            int pos_t = start+1;
            //It should be the same
            while(pos_s < size_s && pos_t < size_t)
            {
                if(s[pos_s] != t[pos_t])
                    return false;
                pos_s++;
                pos_t++;
            }
            return true;
        }
    };```

Log in to reply
 

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