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.
Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
题意解析:
在给定的数组中, 找word1 和 word2 的最短距离
public class Solution {public int shortestDistance(String[] words, String word1, String word2) {// 先找到word1 和 word2, 然后对位置进行做差, 找到最小的距离/* 伪代码:int a = words.indexOf(word1);int b = words.indexOf(word2);int distance = a - b;int min = 0;min = Math.min(min, distance);*/// 从数组中找word1 和word2 的位置,如果找到就将index值赋值给pos// pos用来记录word的位置// 最后将 | pos2 - pos1|求得最小位置差int pos1 = -1;int pos2 = -1;int result = Interger.MAX;for(int i = 0; i < words.length; i++){if (word1.equals(words[i])) {pos1 = i;}else if(word2.equals(words[i])) {pos2 = i;}if (pos1 != -1 && pos2 != -1){int distance = Math.abs(pos2 - pos1);result = Math.min(result, distance);}}return distance;}}
