leetcode243 Shortest Word Distance-zh
# 243. 最短单词距离 (opens new window)
English Version (opens new window)
# 题目描述
给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"]
输入: word1 =“coding”
, word2 =“practice”
输出: 3
输入: word1 ="makes"
, word2 ="coding"
输出: 1
注意:
你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。
# 解法
用两个指针 i1
, i2
保存 word1
和 word2
最近出现的位置,然后每次计算距离 Math.abs(i1 - i2)
是否比此前的记录更小,是则更新最短距离。
# Python3
class Solution:
def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
i1 = i2 = -1
shortest_distance = len(wordsDict)
for i in range(len(wordsDict)):
if wordsDict[i] == word1:
i1 = i
elif wordsDict[i] == word2:
i2 = i
if i1 != -1 and i2 != -1:
shortest_distance = min(shortest_distance, abs(i1 - i2))
return shortest_distance
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# Java
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2) {
int i1 = -1, i2 = -1;
int shortestDistance = wordsDict.length;
for (int i = 0; i < wordsDict.length; ++i) {
if (word1.equals(wordsDict[i])) {
i1 = i;
} else if (word2.equals(wordsDict[i])) {
i2 = i;
}
if (i1 != -1 && i2 != -1) {
shortestDistance = Math.min(shortestDistance, Math.abs(i1 - i2));
}
}
return shortestDistance;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38