Given a list of words and words word1 and Word2, return the shortest distance between these the word s in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “coding”
, word2 = “practice”
, return 3.
Given word1 = "makes"
, word2 = "coding"
, return 1.
Note:
Assume that word1 does not equal to word2, and Word1 and word2 is bot h in the list.
Give a word array and two words, and return the shortest distance of the two words in the array. Assume that two words are different and are in the array.
Java:
public int shortestdistance (string[] words, String word1, String word2) { int m=-1; int n=-1; int min = integer.max_value; for (int i=0; i<words.length; i++) { String s = words[i]; if (Word1.equals (s)) { m = i; if (n!=-1) min = math.min (min, m-n); } else if (word2.equals (s)) { n = i; if (m!=-1) min = math.min (min, n-m); } } return min;}
Python:
# Time: O (N) # Space:o (1) class solution: # @param {string[]} words # @param {string} word1 # @param {Strin G} word2 # @return {integer} def shortestdistance (self, words, word1, word2): dist = float ("inf") I, index1, Index2 = 0, none, none while i < Len (words): if words[i] = = Word1: 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 shortestdistance (vector<string>& words, String word1, String word2) { int P1 =-1, p2 =-1, res = Int_max; for (int i = 0; i < words.size (); ++i) { if (words[i] = = word1) P1 = i; else if (words[i] = = word2) P2 = i; if (P1! =-1 && P2! =-1) res = min (res, ABS (P1-P2)); } return res; }};
C++:
Class Solution {public: int shortestdistance (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 &&am P WORDS[IDX]! = Words[i]) { res = min (res, I-IDX); } idx = i; } } return res; }};
Similar topics:
[Leetcode] 244. Shortest word Distance II shortest word Distance II
[Leetcode] 245. Shortest word Distance III shortest word Distance III
[Leetcode] 243. Shortest word Distance shortest word distance