Skip to content

Latest commit

 

History

History
47 lines (41 loc) · 1.32 KB

245.shortest-word-distance-iii.md

File metadata and controls

47 lines (41 loc) · 1.32 KB

给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。

word1 和 word2  是有可能相同的,并且它们将分别表示为列表中两个独立的单词。

示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"].

输入: word1 = “makes”, word2 = “coding”
输出: 1
输入: word1 = "makes", word2 = "makes"
输出: 3
注意:
你可以假设 word1 和 word2 都在列表里。

244 题基础上加一限制条件,相同位置不计算距离

class Solution {
public:
    unordered_map<string, vector<int>> dict;
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
        for (int i =0; i< words.size(); i++){
            dict[words[i]].push_back(i);
        }
        int step = INT_MAX;
        for (int i = 0; i< dict[word1].size(); i++){
            for (int j = 0; j< dict[word2].size(); j++){
                int p = dict[word1][i];
                int q = dict[word2][j];
                if (p < q) {
                    if (q -p < step) step =q - p;
                    else break;
                }else if (p == q){
                    continue;
                }else {
                    if (p-q <step) step = p-q;
                }
            }
        }
        return step;
    }
};