class WordDistance {
public:
WordDistance(vector<string>& wordsDict) {
}
int shortest(string word1, string word2) {
}
};
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance* obj = new WordDistance(wordsDict);
* int param_1 = obj->shortest(word1,word2);
*/
type WordDistance map[string][]int
func Constructor(wordsDict []string) WordDistance {
indicesMap := WordDistance{}
for i, word := range wordsDict {
indicesMap[word] = append(indicesMap[word], i)
}
return indicesMap
}
func (indicesMap WordDistance) Shortest(word1, word2 string) int {
ans := math.MaxInt32
indices1 := indicesMap[word1]
indices2 := indicesMap[word2]
i, n := 0, len(indices1)
j, m := 0, len(indices2)
for i < n && j < m {
index1, index2 := indices1[i], indices2[j]
ans = min(ans, abs(index1-index2))
if index1 < index2 {
i++
} else {
j++
}
}
return ans
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func min(a, b int) int {
if a > b {
return b
}
return a
}
/**
* Your WordDistance object will be instantiated and called as such:
* obj := Constructor(wordsDict);
* param_1 := obj.Shortest(word1,word2);
*/
class WordDistance {
Map<String, List<Integer>> indicesMap = new HashMap<String, List<Integer>>();
public WordDistance(String[] wordsDict) {
int length = wordsDict.length;
for (int i = 0; i < length; i++) {
String word = wordsDict[i];
indicesMap.putIfAbsent(word, new ArrayList<Integer>());
indicesMap.get(word).add(i);
}
}
public int shortest(String word1, String word2) {
List<Integer> indices1 = indicesMap.get(word1);
List<Integer> indices2 = indicesMap.get(word2);
int size1 = indices1.size(), size2 = indices2.size();
int pos1 = 0, pos2 = 0;
int ans = Integer.MAX_VALUE;
while (pos1 < size1 && pos2 < size2) {
int index1 = indices1.get(pos1), index2 = indices2.get(pos2);
ans = Math.min(ans, Math.abs(index1 - index2));
if (index1 < index2) {
pos1++;
} else {
pos2++;
}
}
return ans;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(wordsDict);
* int param_1 = obj.shortest(word1,word2);
*/
class WordDistance:
def __init__(self, wordsDict: List[str]):
self.indicesMap = defaultdict(list)
for i, word in enumerate(wordsDict):
self.indicesMap[word].append(i)
def shortest(self, word1: str, word2: str) -> int:
ans = inf
indices1 = self.indicesMap[word1]
indices2 = self.indicesMap[word2]
i, n = 0, len(indices1)
j, m = 0, len(indices2)
while i < n and j < m:
index1, index2 = indices1[i], indices2[j]
ans = min(ans, abs(index1 - index2))
if index1 < index2:
i += 1
else:
j += 1
return ans
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)