[CareerCup] 18.5 Shortest Distance between Two Words 两单词间的最短距离

本文提供了解决LeetCode上短词距离问题的三种不同算法实现方案,包括一次调用的简单遍历方法,多次调用的预处理哈希映射方法,以及应对相同单词的情况。

 

18.5 You have a large text file containing words. Given any two words, find the shortest distance (in terms of number of words) between them in the file. If the operation will be repeated many times for the same file (but different pairs of words), can you optimize your solution? 

 

LeetCode上的原题,请参见我之前的博客Shortest Word DistanceShortest Word Distance II和 Shortest Word Distance III

 

解法一:

// Call One Time
int shortest_dist(vector<string> words, string word1, string word2) {
    int p1 = -1, p2 = -1, res = INT_MAX;
    for (int i = 0; i < words.size(); ++i) {
        if (words[i] == word1) p1 = i;
        if (words[i] == word2) p2 = i;
        if (p1 != -1 && p2 != -1) res = min(res, abs(p1 - p2));
    }
    return res;
}

 

解法二:

// Call Many Times
int shortest_dist(vector<string> words, string word1, string word2) {
    unordered_map<string, vector<int>> m;
    int i = 0, j = 0, res = INT_MAX;
    for (int i = 0; i < words.size(); ++i) {
        m[words[i]].push_back(i);
    }
    while (i < m[word1].size() && j < m[word2].size()) {
        res = min(res, abs(m[word1][i] - m[word2][j]));
        m[word1][i] < m[word2][j] ? ++i : ++j;
    }
    return res;
}

 

解法三:

// word1, word2 may be same
int shortest_dist(vector<string> words, string word1, string word2) {
    int p1 = words.size(), p2 = -words.size(), res = INT_MAX;
    for (int i = 0; i < words.size(); ++i) {
        if (words[i] == word1) p1 = word1 == word2 ? p2 : i;
        if (words[i] == word2) p2 = i;
        res = min(res, abs(p1 - p2));
    }
    return res;
}

 

CareerCup All in One 题目汇总

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值