[leetcode] 245. Shortest Word Distance III 解题报告

题目链接: https://leetcode.com/problems/shortest-word-distance-iii/

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same asword2.

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

word1 and word2 may be the same and they represent two individual words in the list.

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

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

Note:
You may assume word1 and word2 are both in the list.


思路: 和上题一样, 用hash表将每一个单词的位置保存起来, 因为一个单词可能在字典中出现多次, 因此hash表的value是一个数组. 然后如果两个单词一样的话就搜索那个单词对于的hash表, 然后找出最小距离. 如果不同的单词就遍历每一个单词,找出最小距离.

代码如下;

class Solution {
public:
    int shortestWordDistance(vector<string>& words, string word1, string word2) {
        unordered_map<string, vector<int>> hash;
        for(int i = 0; i< words.size(); i++)
            hash[words[i]].push_back(i);
        int Min = INT_MAX;
        if(word1 == word2)
            for(int i = 0; i< hash[word1].size()-1; i++)
                Min = min(Min, hash[word1][i+1] - hash[word1][i]);
        else
            for(int i = 0; i < hash[word1].size(); i++)
                for(int j =0; j< hash[word2].size(); j++)
                    Min = min(abs(hash[word1][i] - hash[word2][j]), Min);
        return Min;
    }
};


你可能感兴趣的:(LeetCode,String,hash)