My 4ms easy-to-understand C++ solution


  • 0
    T
    class Solution {
    public:
        bool isOneEditDistance(string s, string t) {
            int nS = s.length();
            int nT = t.length();
            int count, i;
            if(nS == nT) // only one character difference to MODIFY
            {
                count = 0;
                for(i=0; i<nS; i++)
                    if(s[i] != t[i])
                        count++;
                        
                return (count==1);
            }
            else if(nS == nT+1) // only one character in string s to delete
            {
                for(i=0; i<nT; i++)
                    if(s[i]!=t[i])
                        break;
                        
                if(i==nT)
                    return true;
                else 
                    return (s.substr(i+1, nS-i) == t.substr(i, nT-i+1));
            }
            else if(nT == nS+1)
                return isOneEditDistance(t, s); // using symmetry
                
            else
                return false;
        }
    };

Log in to reply
 

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