Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"],
word1 = "makes", word2 = "makes"
makes index [1, 4]
Output: 3
class Solution {
public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
int a = -1;
int b = -1;
int min = Integer.MAX_VALUE;
for (int i = 0; i < wordsDict.length; i++) {
if (wordsDict[i].equals(word1)) {
a = i;// first match: 1, second match: 4
}
if (wordsDict[i].equals(word2)) { // 243 + only add this
if (word1.equals(word2)) { // 243 + only add this
a = b; // first match: a = 1 => a = -1(b), second match: -1 => 1(b)
}
b = i;// orign: -1, first match: 1, second match: 4
}
if (a != -1 && b != -1) {
min = Math.min(min, Math.abs(a - b));
}
}
return min;
}
}
if use 244... 應該只要多加這個判斷, 同樣的 word1 word2, 最小距離會在相臨的
if (word1.equals(word2)) {
for (int i = 0; i < data1.size() - 1; i++) {
min = Math.min(min, Math.abs(data1.get(i) - data1.get(i+1)));
}
return min;
}