Leetcode 0245: Shortest Word Distance III

题目描述:

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.

Example :

Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].

Input: word1 = “makes”, word2 = “coding”
Output: 1

Input: word1 = “makes”, word2 = “makes”
Output: 3

Note:

You may assume word1 and word2 are both in the list.

Time complexity: O(n)
沿用Leetcode 0243: Shortest Word Distance的解法。用两个指针index1和index2分别记录word1和word2最近出现的位置,每次找到新的单词是二者中的一个,则计算差值并与之前的差值比较取最小值。注意因为单词可能相同所以要多加一个判断, 在找到word1且单词相同时把index1 赋值给index2,然后index1 为新的值,以此保持index1 和index2 不相同。

class Solution {
    
    
    
    public int shortestWordDistance(String[] words, String word1, String word2) {
    
    
        int min = Integer.MAX_VALUE, index1 = words.length, index2 = -words.length;
        boolean isSame = word1.equals(word2);
        for (int i = 0; i < words.length; i++) {
    
    
            if(words[i].equals(word1)){
    
    
                if(isSame){
    
    
                    index2 = index1;
                }
                index1 = i;
            }else if(words[i].equals(word2)){
    
    
                index2 = i;
            }
            min = Math.min(Math.abs(index1-index2), min);
        }
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43946031/article/details/113940761