Shortest Word Distance
Last updated
def shortestDistance(words: Array[String], word1: String, word2: String) = {
var minDist = Int.MaxValue
var (word1Index, word2Index) = (-1, -1)
for ((word, i) <- words.zipWithIndex) {
if (word == word1) word1Index = i
else if (word == word2) word2Index = i
if (word1Index != -1 && word2Index != -1) minDist = minDist min math.abs(word1Index - word2Index)
}
minDist
}
val words = Array("practice", "makes", "perfect", "coding", "makes")
shortestDistance(words, "coding", "practice")
shortestDistance(words, "makes", "coding")
/**
* Follow up
* https://leetcode.com/problems/shortest-word-distance-ii/
*
* @param words
*/
class WordDistance(words: Array[String]) {
val indexes: Map[String, Array[Int]] = (for {
(word, i) <- words zipWithIndex
} yield (word, i)).groupBy(_._1).mapValues(_.map(_._2))
def shortest(word1: String, word2: String): Int = {
var minDist = Int.MaxValue
for (x <- indexes(word1); y <- indexes(word2)) {
minDist = minDist min math.abs(x - y)
}
minDist
}
}
val wd = new WordDistance(words)
wd.shortest("coding", "practice")
wd.shortest("makes", "coding")
/**
* Follow up
*
* @param words
* @param word1
* @param word2
* @return
*/
def shortestDistanceIII(words: Array[String], word1: String, word2: String) = {
var minDist = Int.MaxValue
var (word1Index, word2Index) = (-1, -1)
val sameWord: Boolean = word1 == word2
for ((word, i) <- words.zipWithIndex) {
if (sameWord && word == word1) {
word1Index = word2Index
word2Index = i
} else {
if (word == word1) word1Index = i
else if (word == word2) word2Index = i
}
if (word1Index != -1 && word2Index != -1) minDist = minDist min math.abs(word1Index - word2Index)
}
minDist
}
shortestDistanceIII(words, "makes", "coding")
shortestDistanceIII(words, "makes", "makes")