Recent word from

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/iov3Rain/article/details/90414894

Title Description

There is an article containing more than one word, are given two words, please design an efficient algorithm to find the shortest distance from the text of the two words (that is, the minimum number of words apart, that is, the position of the two words in the article absolute value of difference).

Given a string array article, the representative of the given article, but the article number given to the word n ​​and to be looking for two words x and y. Please return the shortest distance between two words. To ensure that the two words are not the same as appears in the text, while ensuring that the article word count 1,000 or less.

 

class Distance {
public:
    int getDistance(vector<string> article, int n, string x, string y) {
        // write code here
        int ans = n - 1;
        int posx = -1, posy = -1;
        for(int i = 0; i < n; ++i)
        {
            if(article[i] == x)
            {
                posx = i;
                if(posy != -1)
                    ans = min(ans, abs(posx - posy));
            }
            else if(article[i] == y)
            {
                posy = i;
                if(posx != -1)
                    ans = min(ans, abs(posx - posy));
            }
        }
        return ans;
    }
};

 

Guess you like

Origin blog.csdn.net/iov3Rain/article/details/90414894