2015年10月29日星期四

Shortest Word Distance III leetcode

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
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.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Given word1 = “makes”word2 = “coding”, return 1.
Given word1 = "makes"word2 = "makes", return 3.
与Shortest Word Distance I唯一不同点就是要考虑一个word1 和Word2相等的情况, 这样的话只更新index1

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

没有评论:

发表评论