Shortest Word Distance
Description
null
Solution(javascript)
// /** 1: Brute Force
// * @param {string[]} words
// * @param {string} word1
// * @param {string} word2
// * @return {number}
// */
// const shortestDistance = function (words, word1, word2) {
// const position1 = []
// const position2 = []
// for (let i = 0; i < words.length; i++) {
// const word = words[i]
// if (word === word1) {
// position1.push(i)
// }
// if (word === word2) {
// position2.push(i)
// }
// }
// let min = Infinity
// for (let i = 0; i < position1.length; i++) {
// for (let j = 0; j < position2.length; j++) {
// min = Math.min(
// min,
// Math.abs(position1[i] - position2[j]),
// )
// }
// }
// return min
// }
/** 1: One Pass
* 分别记录两次单词的位置
* @param {string[]} words
* @param {string} word1
* @param {string} word2
* @return {number}
*/
const shortestDistance = function (words, word1, word2) {
let position1 = -1
let position2 = -1
let min = Infinity
for (let i = 0; i < words.length; i++) {
const word = words[i]
if (word === word1) {
position1 = i
}
if (word === word2) {
position2 = i
}
if (position1 !== -1 && position2 !== -1) {
min = Math.min(
min,
Math.abs(position1 - position2),
)
}
}
return min
}