Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/shortest-word-distance/
- /**
- * Compare each word with word1 and word2 and store the minimum distance seen
- * till now.
- *
- * Time Complexity: O(L * N)
- *
- * Space Complexity: O(1)
- *
- * N = Number of words in words array. L = Average length of a word in words
- * array.
- */
- class Solution {
- public int shortestDistance(String[] words, String word1, String word2) {
- if (words == null || words.length == 0 || word1 == null || word2 == null) {
- return -1;
- }
- int result = Integer.MAX_VALUE;
- int index1 = -1;
- int index2 = -1;
- for (int i = 0; i < words.length; i++) {
- if (words[i].equals(word1)) {
- index1 = i;
- }
- if (words[i].equals(word2)) {
- index2 = i;
- }
- if (index1 != -1 && index2 != -1) {
- result = Math.min(result, Math.abs(index1 - index2));
- }
- }
- return result == Integer.MAX_VALUE ? -1 : result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement