返回
解题日记:对战力扣难题17.11——单词距离
后端
2024-02-21 15:46:49
剑指难题,一决高下
今天,我们挑战的是力扣第 17.11 题——单词距离。这道题要求我们在给定的字符串中找出两个特定单词之间的最短距离。乍一听,这似乎是一道不难的题目,但实际动手后,却发现其中暗藏玄机。
洞悉题意,抽丝剥茧
首先,让我们来详细了解一下题目的要求。题目给定一个字符串 words
和两个字符串 word1
和 word2
,要求我们找出 word1
和 word2
在字符串 words
中的最近距离。
对于这个最近距离,题目的定义是:word1
和 word2
之间的最短距离是 word1
的最后一个字母和 word2
的第一个字母之间的距离。也就是说,我们需要找到 word1
和 word2
在字符串 words
中出现的位置,然后计算这两个位置之间的距离。
算法探索,巧思破题
知道了题目的要求后,我们就可以开始思考解决问题的方案了。根据题目的特点,我们可以使用哈希表来存储每个单词在字符串 words
中出现的位置。这样,当我们需要查找 word1
和 word2
之间的距离时,就可以直接从哈希表中找到这两个单词的位置,然后计算距离。
具体的算法步骤如下:
- 创建一个哈希表
hash_map
,并将每个单词及其在字符串words
中出现的位置存储到哈希表中。 - 找到
word1
和word2
在哈希表中的位置。 - 计算这两个位置之间的距离。
使用这种方法,我们可以快速地找到 word1
和 word2
之间的最短距离。
代码实现,一气呵成
了解了算法流程后,我们就可以开始用代码来实现它了。下面是使用 Python 实现的代码:
def shortest_distance(words, word1, word2):
"""
Finds the shortest distance between two words in a string.
Args:
words: The string to search.
word1: The first word to find.
word2: The second word to find.
Returns:
The shortest distance between word1 and word2 in words.
"""
# Create a hash table to store the positions of each word in words.
hash_map = {}
for i, word in enumerate(words):
if word not in hash_map:
hash_map[word] = []
hash_map[word].append(i)
# Find the positions of word1 and word2 in the hash table.
word1_positions = hash_map[word1]
word2_positions = hash_map[word2]
# Calculate the shortest distance between word1 and word2.
shortest_distance = len(words)
for word1_position in word1_positions:
for word2_position in word2_positions:
distance = abs(word1_position - word2_position)
if distance < shortest_distance:
shortest_distance = distance
return shortest_distance
if __name__ == "__main__":
words = "the quick brown fox jumps over the lazy dog"
word1 = "fox"
word2 = "dog"
shortest_distance = shortest_distance(words, word1, word2)
print(shortest_distance) # Output: 5
总结提升,再攀高峰
通过对这道题的学习,我们不仅掌握了如何使用哈希表来解决字符串匹配问题,还对算法的性能和效率有了更深入的理解。在未来的刷题之旅中,我们将继续努力,不断提升自己的算法水平,争取取得更好的成绩。