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;
    }
}

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《LeetCode – 243. Shortest Word Distance》

153
0 0 153

延伸阅读

发表回复

登录后才能评论
分享本页
返回顶部