Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"],
word1 = "makes", word2 = "makes"
makes index [1, 4]
Output: 3
classSolution {publicintshortestWordDistance(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 thisif (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;
}