This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
word1 and word2 may be the same and they represent two individual words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “makes”
, word2 = “coding”
, return 1.
Given word1 = "makes"
, word2 = "makes"
, return 3.
Note:
You may assume word1 and word2 are both in the list.
Solution:
When word1==word2, update both p1 and p2 regularly and compute minDis for each update except when p2 updated and get p2==p1.
1 public class Solution { 2 public int shortestWordDistance(String[] words, String word1, String word2) { 3 if (words.length<2) return -1; 4 5 int p1 = -words.length, p2 = -words.length; 6 int minDis = Integer.MAX_VALUE; 7 for (int i=0;i<words.length;i++){ 8 if (!words[i].equals(word1) && !words[i].equals(word2)) continue; 9 10 if (words[i].equals(word1)){ 11 p1 = i; 12 minDis = Math.min(minDis,Math.abs(p1-p2)); 13 } 14 15 if (words[i].equals(word2)){ 16 p2 = i; 17 if (p2!=p1) minDis = Math.min(minDis,Math.abs(p1-p2)); 18 } 19 } 20 return minDis; 21 } 22 }