Leetcode - Shortest Word Distance III

My code:

public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int i1 = -1;
        int i2 = -1;
        int ret = Integer.MAX_VALUE;
        if (word1.equals(word2)) {
            for (int i = 0; i < words.length; i++) {
                if (words[i].equals(word1)) {
                    if (i2 < i1) {
                        i2 = i;
                    }
                    else {
                        i1 = i;
                    }
                }
                if (i1 != -1 && i2 != -1) {
                    ret = Math.min(ret, Math.abs(i1 - i2));
                }
            }
        }
        else {
            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/ae70d4d7b5b6#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞