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 的最短距离

    1. public class Solution {
    2. public int shortestDistance(String[] words, String word1, String word2) {
    3. // 先找到word1 word2, 然后对位置进行做差, 找到最小的距离
    4. /* 伪代码:
    5. int a = words.indexOf(word1);
    6. int b = words.indexOf(word2);
    7. int distance = a - b;
    8. int min = 0;
    9. min = Math.min(min, distance);
    10. */
    11. // 从数组中找word1 word2 的位置,如果找到就将index值赋值给pos
    12. // pos用来记录word的位置
    13. // 最后将 | pos2 - pos1|求得最小位置差
    14. int pos1 = -1;
    15. int pos2 = -1;
    16. int result = Interger.MAX;
    17. for(int i = 0; i < words.length; i++){
    18. if (word1.equals(words[i])) {
    19. pos1 = i;
    20. }else if(word2.equals(words[i])) {
    21. pos2 = i;
    22. }
    23. if (pos1 != -1 && pos2 != -1){
    24. int distance = Math.abs(pos2 - pos1);
    25. result = Math.min(result, distance);
    26. }
    27. }
    28. return distance;
    29. }
    30. }