TreeviewCopyright © aleen42 all right reserved, powered by aleen42
11. 单词距离
https://leetcode-cn.com/problems/find-closest-lcci/
Java
class Solution {
public int findClosest(String[] words, String word1, String word2) {
int indexWord1 = -1, indexWord2 = -1, minDistance = 0;
for(int i = 0; i < words.length; i++) {
if(words[i].equals(word1)) indexWord1 = i;
if(words[i].equals(word2)) indexWord2 = i;
if(indexWord1 != -1 && indexWord2 != -1) {
if(minDistance == 0) minDistance = Math.abs(indexWord1 - indexWord2);
minDistance = Math.min(minDistance, Math.abs(indexWord1 - indexWord2));
}
}
return minDistance;
}
}
Python
'''
Author: Goog Tech
Date: 2020-08-30 22:45:41
LastEditTime: 2020-08-30 22:46:02
Description: https://leetcode-cn.com/problems/find-closest-lcci/
FilePath: \leetcode-googtech\面试题17\#11. 单词距离\Solution.py
WebSite: https://algorithm.show/
'''
class Solution(object):
def findClosest(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
indexWorld1, indexWorld2, minDistance = -1, -1, 0
for i in range(len(words)):
if words[i] == word1: indexWorld1 = i
if words[i] == word2: indexWorld2 = i
if indexWorld1 != -1 and indexWorld2 != -1:
if minDistance == 0:
minDistance = abs(indexWorld1 - indexWorld2)
minDistance = min(minDistance, abs(indexWorld1 - indexWorld2))
return minDistance