Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Simply store indices in ctor.

class WordDistance {
    unordered_map<string, vector<int>> hm;
public:
    WordDistance(vector<string>& words) {
        for (int i = 0; i < words.size(); i++)
        {
            hm[words[i]].push_back(i);
        }
    }

    int shortest(string word1, string word2) {
        vector<int> &vec1 = hm[word1];
        vector<int> &vec2 = hm[word2];
        
        int ret = INT_MAX;
        int i1 = 0, i2 = 0;
        while (i1 < vec1.size() && i2 < vec2.size())
        {
            int v1 = vec1[i1], v2 = vec2[i2];
            ret = std::min(ret, abs(v1 - v2));
            if (v1 < v2) i1++;
            else i2++;
        }
        return ret;
    }
};
View Code
posted on 2015-08-22 11:18  Tonix  阅读(174)  评论(0编辑  收藏  举报