Advertisement
1988coder

245. Shortest Word Distance III

Jan 15th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/shortest-word-distance-iii/
  2.  
  3. /**
  4.  * Refer :
  5.  * https://leetcode.com/problems/shortest-word-distance-iii/discuss/67097/12-16-lines-Java-C++
  6.  *
  7.  * Time Complexity: O(L * N)
  8.  *
  9.  * Space Complexity: O(1)
  10.  *
  11.  * L = Average length of a word in words array. N = Number words in the input
  12.  * array.
  13.  */
  14. class Solution {
  15.     public int shortestWordDistance(String[] words, String word1, String word2) {
  16.         if (words == null || words.length == 0 || word1 == null || word2 == null) {
  17.             return -1;
  18.         }
  19.  
  20.         boolean same = word1.equals(word2);
  21.         int result = Integer.MAX_VALUE;
  22.         int index1 = -1;
  23.         int index2 = -1;
  24.  
  25.         for (int i = 0; i < words.length; i++) {
  26.             if (words[i].equals(word1)) {
  27.                 index1 = i;
  28.             }
  29.             if (words[i].equals(word2)) {
  30.                 if (same) {
  31.                     // In case of word1 == word2, index1 will store the previous occurance of the
  32.                     // word.
  33.                     index1 = index2;
  34.                 }
  35.                 index2 = i;
  36.             }
  37.             if (index1 != -1 && index2 != -1) {
  38.                 result = Math.min(result, Math.abs(index1 - index2));
  39.             }
  40.         }
  41.  
  42.         return result == Integer.MAX_VALUE ? -1 : result;
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement