slight modification to shortest distance 1 with simple while loop


  • 0
    V
    int i = -1;
            int j = -1;
            int k = 0;
            int min = int.MaxValue;
            bool sameword = word1 == word2;
            bool foundword = false;
    
            while(k < words.Length)
            {
                if( words[k] == word1)
                {
                    if(!foundword || !sameword)
                    {
                        i = k;
                        foundword = true;
                    }
                }
    
                if(words[k] == word2)
                {
                    if(i != k)
                    {
                        j = k;
                    }
                }
    
                if(i != -1 && j != -1)
                {
                    min = min > Math.Abs(i - j) ? Math.Abs(i - j) : min;
                    if(j > i)
                    {
                        foundword = false;
                    }
                }
    
                k++;
            }
    
            return min;
        }
    
    

Log in to reply
 

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