Shortest Word Distance III
Description
null
Solution(javascript)
/**
* @param {string[]} words
* @param {string} word1
* @param {string} word2
* @return {number}
*/
const shortestWordDistance = function (words, word1, word2) {
let position1 = -1
let position2 = -1
let min = Infinity
const isSame = word1 === word2
for (let i = 0; i < words.length; i++) {
const word = words[i]
if (!isSame) {
if (word === word1) {
position1 = i
}
if (word === word2) {
position2 = i
}
} else if (word === word1) {
if (position1 < position2) {
position1 = i
} else {
position2 = i
}
}
if (position1 !== -1 && position2 !== -1) {
min = Math.min(
min,
Math.abs(position1 - position2),
)
}
}
return min
}