LeetCode 题解(267) : Shortest Word Distance

这是一篇关于LeetCode第267题的解题报告,探讨如何找到给定单词列表中两个指定单词之间的最短距离。文章通过示例解释了问题,并提出了使用HashMap的数据结构来解决此问题的C++实现方案。

题目:

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = "makes", word2 = "coding", return 1.

题解:

HashMap。

C++版:

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        unordered_map<string, vector<int>> d;
        for(int i = 0; i < words.size(); i++) {
            if(d.find(words[i]) == d.end()) {
                vector<int> t(1, i);
                d.insert(pair<string, vector<int>>(words[i], t));
            } else
                d[words[i]].push_back(i);
        }
        int s = INT_MAX;
        for(auto i : d[word1]) {
            for(auto j : d[word2]) {
                int dis = abs(i - j);
                if(dis < s)
                    s = dis;
            }
        }
        return s;
    }
};

Python版:

import sys

class Solution(object):
    def shortestDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        d = {}
        j = 0
        for i in words:
            if i not in d:
                d[i] = [j]
            else:
                d[i].append(j)
            j += 1
        smallest = sys.maxint
        for i in d[word1]:
            for j in d[word2]:
                distance = abs(i - j)
                if distance < smallest:
                    smallest = distance
        return smallest
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值