C# nothing fancy, but only beats 12%, why is that?


  • 0

    This is a pretty standard solution as far as I can tell. But, it only beats 12% of other C# solutions. Is there something that would improve the performance of this routine? I don't see anything here that is inefficient, do you? Thanks!

    public bool IsOneEditDistance(string s, string t) {
        if (s.Length == t.Length)
        {
            return IsReplace(s, t);
        }
        else if (s.Length == t.Length + 1)
        {
            return IsDelete(s, t);
        }
        else if (t.Length == s.Length + 1)
        {
            return IsDelete(t, s);
        }
        else
        {
            return false;
        }
    }
    
    public bool IsReplace(string s, string t)
    {
        int n = 0;
        for (int i = 0; i < s.Length; i++)
        {
            if (s[i] != t[i])
            {
                n++;
            }
        }
        
        return n == 1;
    }
    
    public bool IsDelete(string src, string target)
    {
        int i = 0;
        int j = 0;
        while (i < src.Length)
        {
            if (j < target.Length && src[i] == target[j])
            {
                j++;
            }
            i++;
        }
        
        return i == j + 1;
    }

  • 0

    BTW - I added a condition to terminate the loops early if the greater than 1 diff condition was exceeded. But that actually made my runtime worse! I suppose the condition evaluations are slowing this down? If you have any ideas please share.


Log in to reply
 

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