題目描述
有一篇文章內含多個單詞,現給定兩個單詞,請設計一個高效算法,找出文中這兩個單詞的最短距離(即最少相隔的單詞數,也就是兩個單詞在文章中位置的差的絕對值)。
給定一個string數組article,代表所給文章,同時給定文章的單詞數n和待查找的兩個單詞x和y。請返回兩個單詞的最短距離。保證兩個單詞均在文中出現且不相同,同時保證文章單詞數小於等於1000。
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;
}
};