Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/shortest-word-distance-iii/
- /**
- * Refer :
- * https://leetcode.com/problems/shortest-word-distance-iii/discuss/67097/12-16-lines-Java-C++
- *
- * Time Complexity: O(L * N)
- *
- * Space Complexity: O(1)
- *
- * L = Average length of a word in words array. N = Number words in the input
- * array.
- */
- class Solution {
- public int shortestWordDistance(String[] words, String word1, String word2) {
- if (words == null || words.length == 0 || word1 == null || word2 == null) {
- return -1;
- }
- boolean same = word1.equals(word2);
- 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)) {
- if (same) {
- // In case of word1 == word2, index1 will store the previous occurance of the
- // word.
- index1 = index2;
- }
- 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