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;
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s