This was a follow up of shortest Word Distance. The only difference are now word1 could be the same as Word2.
Given a list of words and words word1 and word2, return the shortest distance between these, words in the list.
Word1 and Word2 is the same and they represent the 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 is both in the list.
243. Shortest Word Distance and 245. Shortest word Distance II, this time two words may be the same.
Python:
# Time: O (N) # Space:o (1) class solution: # @param {string[]} words # @param {string} word1 # @param {Strin G} word2 # @return {integer} def shortestworddistance (self, words, word1, word2): dist = float ("inf") Is_same = (Word1 = = Word2) I, index1, index2 = 0, none, none while i < Len (words): if words[i] = = word1:
if Is_same and index1 are not None: dist = min (dist, ABS (index1-i)) index1 = i elif words[i] = = Word2: Index2 = i if index1 is not none and Index2 are not none: dist = min (dist, ABS (INDEX1-INDEX2)) i + = 1 Return Dist
C++:
Class Solution {public: int shortestworddistance (vector<string>& words, String word1, String word2) { int p1 =-1, p2 =-1, res = Int_max; for (int i = 0; i < words.size (); ++i) { int t = p1; if (words[i] = = word1) P1 = i; if (words[i] = = word2) P2 = i; if (P1! =-1 && P2! =-1) { if (word1 = = Word2 && T! =-1 && t! = p1) { res = min (res, ABS (T-P1)); } else if (p1! = p2) { res = min (res, ABS (P1-P2)) ; }}} return res; }};
C++:
Class Solution {public: int shortestworddistance (vector<string>& words, String word1, String word2) { int p1 = Words.size (), p2 =-words.size (), res = Int_max; for (int i = 0; i < words.size (); ++i) { if (words[i] = = word1) P1 = Word1 = Word2? p2:i; if (words[i] = = word2) P2 = i; res = min (res, ABS (P1-P2)); } return res; }};
C++:
Class Solution {public: int shortestworddistance (vector<string>& words, String word1, String word2) { int idx =-1, res = Int_max; for (int i = 0; i < words.size (); ++i) { if (words[i] = = Word1 | | words[i] = = Word2) { if (idx! =-1 && (word1 = = Word2 | | words[i]! = Words[idx])) { res = min (res, I-IDX); } idx = i; } } return res; }};
Similar topics:
[Leetcode] 243. Shortest word Distance shortest word distance
[Leetcode] 245. Shortest word Distance II shortest word Distance II
[Leetcode] 245. Shortest word Distance III shortest word Distance III