This is a follow up of . 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.
"makes"
, word2 = "makes"
, return 3.
思路:在第一版的基础上加上相同的分支即可。在第一个index上卡住了,想用prev指针但发现很麻烦。其实只要在碰到第一个数的时候只更新指针不变min即可,用初始化负数来区分即可。
if(pos1>=0)
{ min=Math.min(i-pos1,min); } pos1=i;public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { if(words.length==2) { return 1; } int pos1=-1; int pos2=-2; int min=Integer.MAX_VALUE; boolean check=word1.equals(word2); for(int i=0;i=0) { min=Math.min(i-pos1,min); } pos1=i; } } } else { if(words[i].equals(word1)) { pos1=i; } else if(words[i].equals(word2)) { pos2=i; } if(pos1>=0&&pos2>=0) { min=Math.min(Math.abs(pos2-pos1),min); } } } return min; }}