Friday, August 12, 2016

245. Shortest Word Distance III

This is a follow up problem for "243. Shortest Word Distance". I only added line 11-13 which means if the two words are the same, i1 becomes the last appearance, i2 becomes the current appearance. The trick here is i1 and i2 are both initialized to -1. So for case ["a", "a"], word1="a" and word2 = "a", int first round loop, dist become 1. Note for two same words, the minimal distance is 1. So it is fine to have 1 in first round loop.

1:  class Solution {  
2:  public:  
3:    int shortestWordDistance(vector<string>& words, string word1, string word2) {  
4:      int dist = INT_MAX, i1 = -1, i2 = -1;  
5:      for (int i = 0; i < words.size(); i++) {  
6:        if (words[i] == word1) {  
7:          i1 = i;  
8:          if (i2 != -1) dist = min(dist, abs(i2-i1));  
9:        }  
10:        if (words[i] == word2) {  
11:          if (word1 == word2) {  
12:            i1 = i2;  
13:          }  
14:          i2 = i;  
15:          if (i1 != -1) dist = min(dist, abs(i2-i1));  
16:        }  
17:      }  
18:      return dist;  
19:    }  
20:  };  

No comments:

Post a Comment