245. Shortest Word Distance III

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.

一刷
題解:不同于243的是,可以有重復(fù)的元素,如果有重復(fù),那么要分別找到兩個index, 并比較差值。

如果word1和word2相等,那么如果找到

 p1 = p2;
p2 = i;

類似于隊列,保存相鄰的index, 從而比較差值。

如果word1和word2不等,則分別對p1, p2賦值。

public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        boolean same = word1.equals(word2);
        int min = Integer.MAX_VALUE;
        int p1 = -1, p2 = -1;
        for(int i=0; i<words.length; i++){
            if(words[i].equals(word1)){
                if(same){
                    p1 = p2;
                    p2 = i;
                }
                else{
                    p1 = i;
                }
            }
            
            if(!same && words[i].equals(word2)) p2 = i;
            if(p1!=-1 && p2!=-1) min = Math.min(min, Math.abs(p1-p2));
        }
        return min;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容