My c++ solution


  • 1
    L
    bool isOneEditDistance(string s, string t) 
    {
    
    	string &ss = s, &tt = t;
    	if (ss.size() > tt.size()) swap(ss, tt);
    
    	int lens = ss.size(), lent = tt.size();
    	if (lent -lens >= 2) return false;
    
    	int diffcount = 0;
    	int notequal = lens == lent ? 0: 1;
    	
    	for (int i = 0; i < lent; i++)
    	{
    		if (t[i] != s[i - diffcount*notequal])
    		{
    			diffcount++;
    		}
    	}
    
    	return diffcount == 1;
    }

  • 0
    A

    add one more command like

    if(diffcount>1) return false;

    just after

    diffcount++;

    may save more time.


Log in to reply
 

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