Topic:
There is a large text containing the word, given any two words, find out the shortest distance of two words in this file.
Ideas:
Record the last occurrence of the two words by two two variables, and then each time calculate the distance between the two, and update the minimum distance.
Assuming you need to find the shortest distance for any two words repeatedly, you need to construct a hash table that records each word and where it appears. When finding the shortest distance for a two word, just find the location where the difference in the list of the two words is minimized.
Find method: You can merge two ordered lists (the list element contains the position and the word it belongs to, you can construct the structure).
Code:
#include <iostream>#include<vector>#include<limits.h>using namespacestd;intShortest_1 (Constvector<string> &words,stringWord1,stringWord2) { intmin=int_min; intlen=words.size (); intlastword1=-1; intlastword2=-1; intdistance; for(intI=0; i<len;i++){ stringcurword=Words[i]; if(curword==word1) {LastWord1=i; Distance=lastword1-LastWord2; if(lastword2>=0&& min>distance) min=distance; } Else if(curword==Word2) {LastWord2=i; Distance=lastword2-LastWord1; if(lastword1>=0&& min>distance) min=distance; } } returnmin;}intMain () {return 0;}
(algorithm) The shortest distance of two words