careercup-高等难度 18.5

18.5 有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(也即相隔几个单词)。有办法在O(1)时间里完成搜索操作吗?解法的空间复杂度如何?

解法1:我们假设单词word1和word2谁在前谁在后无关紧要。要解决此题,我们需要遍历一次这个文件。在遍历期间,我们会记下最后看见word1和word2的地方,并把它们的位置存入lastPosWord1和lastPosWord2中。碰到word1时,就拿他跟lastPosWord2比较,如有必要则更新min,然后更新lastPosWord1.每碰到word2时,我们也执行同样的操作。遍历结束后,就可以得到最短距离。

实现算法:

int ShortestDist(string text[], int n, string word1, string word2){
    int min = kMaxInt / 2;
    int pos1 = -min;
    int pos2 = -min;

    for(int pos=0; pos<n; ++pos){
        if(text[pos] == word1){
            pos1 = pos;
            int dist = pos1 - pos2;
            if(dist < min)
                min = dist;
        }
        else if(text[pos] == word2){
            pos2 = pos;
            int dist = pos2 - pos1;
            if(dist < min)
                min = dist;
        }
    }

    return min;
}

如果上述代码要重复调用(查询其他单词对的最短距离),可以构造一个散列表,记录每个单词及其出现的位置。然后,我们只需找到listA和listB中(算术)差值最小的那两个值。

hash_map<string,vector<int> > listA;

hash_map<string,vector<int> > listB;

listA:{1,2,9,15,25}

listB:{4,10,19}

原文地址:https://www.cnblogs.com/wuchanming/p/4362321.html