for a string array, given 2 words, find min distance between them.

 

the distance is measured by how many words between these 2 words:

 

public int shortest( String[] words, String word1, String word2 )
{
    if( words.length < 1 )
    {
        return -1
    };
    if( word1 == null || word2 == null )
    {
        return null;
    }

    int pos = 0;
    int word1Pos = 0;
    int word2Pos = 0;
    int min = Integer.Max;

    for( String word : words )
    {
        pos++;
        if( word.equal( word1 )
        {
            word1Pos = pos;
            if( min < Math.abs( word1Pos - word2Pos ) )
            {
                min = Math.abs( word1Pos - word2Pos );
            }
        }
        else if( word.equal( word2 ) )
        {
            word2Pos = pos;
            if( min < Math.abs( word1Pos - word2Pos ) )
            {
                min = Math.abs( word1Pos - word2Pos );
            }
        }
    }

    return min;
}

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a comment