245. Shortest Word Distance III

time: O(n)

space: O(1)

Example 2:

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;
        }

Last updated