243. Shortest Word Distance

题目:

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.

链接: http://leetcode.com/problemset/algorithms/

3/2/2017,

string的比较用equals,不是==

 1 public class Solution {
 2     public int shortestDistance(String[] words, String word1, String word2) {
 3         int index = Integer.MAX_VALUE;
 4         int m = -1, n = -1;
 5         for (int i = 0; i < words.length; i++) {
 6             if (words[i].equals(word1)) {
 7                 if (n != -1 && i - n < index) index = i - n;
 8                 m = i;
 9             } else if (words[i].equals(word2)) {
10                 if (m != -1 && i - m < index) index = i - m;
11                 n = i;
12             }
13         }
14         return index;
15     }
16 }
原文地址:https://www.cnblogs.com/panini/p/6493858.html