【字符串】面试题 17.11. 单词距离
题目:

解答:
1 class Solution { 2 public: 3 int findClosest(vector<string>& words, string word1, string word2) 4 { 5 6 int t1 = -1; 7 int t2 = -1; 8 int res = words.size(); 9 10 for (int i = 0; i < words.size(); i ++) 11 { 12 if (words[i] == word1) 13 { 14 t1 = i; 15 } 16 else if (words[i] == word2) 17 { 18 t2 = i; 19 } 20 if (t1 != -1 && t2 != -1) 21 { 22 res = min(res, abs(t1 - t2)); 23 } 24 if (res == 1) 25 { 26 break; 27 } 28 } 29 return res; 30 } 31 };

浙公网安备 33010602011771号