Shortest Word Distance II
Description
null
Solution(javascript)
/**
* @param {string[]} words
*/
const WordDistance = function (words) {
this.map = words.reduce((acc, word, index) => {
acc[word] = acc[word] || []
acc[word].push(index)
return acc
}, {})
}
/**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
WordDistance.prototype.shortest = function (word1, word2) {
const list1 = this.map[word1]
const list2 = this.map[word2]
let min = Infinity
let i = 0
let j = 0
while (i < list1.length && j < list2.length) {
min = Math.min(
min,
Math.abs(
list1[i] - list2[j],
),
)
if (list1[i] < list2[j]) {
i++
} else {
j++
}
}
return min
}
/**
* Your WordDistance object will be instantiated and called as such:
* var obj = new WordDistance(words)
* var param_1 = obj.shortest(word1,word2)
*/