Shortest Word Distance III in C++

C++Server Side ProgrammingProgramming

Suppose we have a list of words and another two words called word1 and word2, we have to find the shortest distance between these two words in the list. Here word1 and word2 may be the same and they represent two individual words in the list. Let us assume that words = ["practice", "makes", "perfect", "skill", "makes"].

So, if the input is like word1 = “makes”, word2 = “skill”, then the output will be 1

To solve this, we will follow these steps −

  • ret := 10^9, l1 := 10^9, l2 := -10^9

  • n := size of words

  • for initialize i := 0, when i < n, update (increase i by 1), do −

    • if words[i] is same as word1, then −

      • l1 := i

    • if words[i] is same as word2, then −

      • if word1 is same as word2, then −

        • l1 := l2

      • l2 := i

    • ret := minimum of |l2 - l1| and ret

  • return ret

Example 

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int shortestWordDistance(vector<string<& words, string word1, string word2) {
      int ret = 1e9;
      int l1 = 1e9;
      int l2 = -1e9;
      int n = words.size();
      for (int i = 0; i < n; i++) {
         if (words[i] == word1) {
            l1 = i;
         }
         if (words[i] == word2) {
            if (word1 == word2) {
               l1 = l2;
            }
            l2 = i;
         }
         ret = min(abs(l2 - l1), ret);
      }
      return ret;
   }
};
main(){
   Solution ob;
   vector<string< v = {"practice", "makes", "perfect", "skill", "makes"};
   cout << (ob.shortestWordDistance(v, "makes", "skill"));
}

Input

{"practice", "makes", "perfect", "skill", "makes"},"makes", "skill"

Output

1
raja
Published on 18-Nov-2020 11:19:09
Advertisements