245 Shortest Word Distance III

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

For example, Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “makes”, word2 = “coding”, return 1.

Given word1 = "makes", word2 = "makes", return 3.

Note: You may assume word1 and word2 are both in the list.

  #include <iostream>
  #include <vector>
  #include <math.h>
  #include <algorithm>

  using namespace std;

  int shortestDistance(vector<string> *words, string word1, string word2)
  {

      vector<int> minElements;
      vector<int> word1Positions;
      vector<int> word2Positions;

      int word1Pos, word2Pos;
      int size = (*words).size();

      for (int i = 0; i < size; i++)
      {
          // store all positions of first word
          string currentWord = (*words).at(i);
          if (currentWord == word1)
              word1Positions.push_back(i);
          if (currentWord == word2)
              word2Positions.push_back(i);
      }

      // find the minimum displacement between each word
      int difference;
      int j = 0;
      while (word2Positions.size() > j)
      {
          for (int i = 0; i < word1Positions.size(); i++)
          {
              difference = abs(((word1Positions).at(i)) - ((word2Positions).at(j)));
              minElements.push_back(difference);
          }
          j++;
      }

      // if the words all the same we simply look for the maxElement because a minElement would be we overlapped (would be 0).
      if (word1 == word2)
      {
          int maxElement = *max_element(minElements.begin(), minElements.end());
          cout << maxElement << endl;
          return maxElement;
      }
      else
      {
          int minElement = *min_element(minElements.begin(), minElements.end());
          cout << minElement << endl;
          return minElement;
      }
  }

  int main()
  {
      vector<string> words = { "practice", "makes", "perfect", "coding", "makes" };

      string word1 = "coding", word2 = "practice"; // 3
      string word3 = "makes", word4 = "coding"; // 1

      shortestDistance(&words, word1, word2);
      shortestDistance(&words, word3, word4);
  }

Last updated