LeetCode – 243. Shortest Word Distance


Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.

Note:
You may assume that word1does not equal toword2, and word1 and word2 are both in the list.

这道题小心重复

public class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int w1 = -1;
        int w2 =-1;
        int min = Integer.MAX_VALUE;
        for(int i=0; i<words.length;i++){
            if(words[i].equals(word1)){
                w1 = i;
            }
            if(words[i].equals(word2)){
                w2 = i;
            }
            if(w1 != -1 && w2 != -1){
                if(Math.abs(w1-w2)<min){
                    min = Math.abs(w1-w2);
                }
                
            }
        }   
        return min;
    }
}

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。