only 9 lines c++ solution with explanation


  • 0
    bool isOneEditDistance(string s, string t) {
            int m = s.length(), n = t.length(), cnt = 0;   //cnt counts the number of distances
            for(int i = 0, j = 0; (i<m || j<n) && cnt<=1; i++,j++){
                if(s[i]!=t[j]){
                    cnt++;
                    if(m<n)i--;   //if m<n, then t[j] goes to t[j+1] while s[i] stays
                    if(m>n)j--;   //if m>n, then s[i] goes to s[i+1] while t[j] stays
                }
            }
            return cnt==1;      
        }
    

  • 0

    Is it good enough?


Log in to reply
 

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