Advertisement
1988coder

243. Shortest Word Distance

Jan 15th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/shortest-word-distance/
  2.  
  3. /**
  4.  * Compare each word with word1 and word2 and store the minimum distance seen
  5.  * till now.
  6.  *
  7.  * Time Complexity: O(L * N)
  8.  *
  9.  * Space Complexity: O(1)
  10.  *
  11.  * N = Number of words in words array. L = Average length of a word in words
  12.  * array.
  13.  */
  14. class Solution {
  15.     public int shortestDistance(String[] words, String word1, String word2) {
  16.         if (words == null || words.length == 0 || word1 == null || word2 == null) {
  17.             return -1;
  18.         }
  19.  
  20.         int result = Integer.MAX_VALUE;
  21.         int index1 = -1;
  22.         int index2 = -1;
  23.  
  24.         for (int i = 0; i < words.length; i++) {
  25.             if (words[i].equals(word1)) {
  26.                 index1 = i;
  27.             }
  28.             if (words[i].equals(word2)) {
  29.                 index2 = i;
  30.             }
  31.             if (index1 != -1 && index2 != -1) {
  32.                 result = Math.min(result, Math.abs(index1 - index2));
  33.             }
  34.         }
  35.  
  36.         return result == Integer.MAX_VALUE ? -1 : result;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement