[CTCI] 单词最近距离

单词最近距离

题目描述

有一篇文章内含多个单词,现给定两个单词,请设计一个高效算法,找出文中这两个单词的最短距离(即最少相隔的单词数,也就是两个单词在文章中位置的差的绝对值)。

给定一个string数组article,代表所给文章,同时给定文章的单词数n和待查找的两个单词xy。请返回两个单词的最短距离。保证两个单词均在文中出现且不相同,同时保证文章单词数小于等于1000。

 1 class Distance {
 2 public:
 3     int getDistance(vector<string> article, int n, string x, string y) {
 4         // write code here
 5         int px = -1, py = -1;
 6         int res = n;
 7         for (int i = 0; i < n; ++i) {
 8             if (article[i] == x) {
 9                 px = i;
10                 if (py != -1) res = min(res, px - py);
11             } else if (article[i] == y) {
12                 py = i;
13                 if (px != -1) res = min(res, py - px);
14             }
15         }
16         return res;
17     }
18 };

 

posted @ 2015-07-26 14:20  Eason Liu  阅读(414)  评论(0编辑  收藏  举报