(algorithm) The shortest distance of two words

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.