【LeetCode刷题】--245.最短单词距离III

245.最短单词距离III

【LeetCode刷题】--245.最短单词距离III_第1张图片

class Solution {
    public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
        int len = wordsDict.length;
        int ans = len;
        if(word1.equals(word2)){
            int prev = -1;
            for(int i = 0;i<len;i++){
                String word = wordsDict[i];
                if(word.equals(word1)){
                    if(prev >= 0){
                        ans = Math.min(ans,i - prev);
                    }
                    prev = i;
                }
            }
        }else{
            int index1 = -1,index2 = -1;
            for(int i = 0;i<len;i++){
                String word = wordsDict[i];
                if(word.equals(word1)){
                    index1 = i;
                }else if(word.equals(word2)){
                    index2 = i;
                }
                if(index1 >= 0 && index2 >= 0){
                    ans = Math.min(ans, Math.abs(index1 - index2));
                }
            }
        }
        return ans;
    }
}

你可能感兴趣的:(LeetCode,leetcode,算法)