/* * 245.Shortest Word Distance III * 2016-6-18 by Mingyang * The only difference is now word1 could be the same as word2. * 这个题目可以分别用以上两种方法分别改装 * 注意两个equal并不代表两个数的距离是0!!!! */
public int shortestWordDistance(String[] words, String word1, String word2) { int len=words.length; if(words==null||len==0) return 0; int first=-1; int second=-1; int res=Integer.MAX_VALUE; if(word1.equals(word2)){ int pre=-1; for(int i=0;i<len;i++){ if(words[i].equals(word1)){ if(pre==-1){ pre=i; continue; }else{ res=Math.min(res,i-pre); pre=i; } } } return res; } for(int i=0;i<len;i++){ if(words[i].equals(word1)){ first=i; } if(words[i].equals(word2)){ second=i; } if(first>=0&&second>=0){ res=Math.min(res,Math.abs(first-second)); } } return res; }