Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example,

Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.

 

思路:一次遍历,碰到就存,因为最短的距离肯定是最新碰到的两个。注意边界即可

public class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        if(words.length==2)
        {
            return 1;
        }
        int pos1=-1;
        int pos2=-2;
        int min=Integer.MAX_VALUE;
        for(int i=0;i<words.length;i++)
        {
            if(words[i].equals(word1))
            {
            pos1=i;
            }
            else if(words[i].equals(word2))
            {
             pos2=i;
            }
            if(pos1>=0&&pos2>=0)
            {
            min=Math.min(Math.abs(pos2-pos1),min);
            }
        }
        
        return min;
    }
}

 

posted on 2016-09-21 11:40  Machelsky  阅读(123)  评论(0)    收藏  举报