Leetcode - Shortest Word Distance

My code:

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

比较简单。

Anyway, Good luck, Richardo! — 09/05/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/ed2a955e7e4f#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞