245. Shortest Word Distance III

题目:

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.

Note:
You may assume word1 and word2 are both in the list.

链接: http://leetcode.com/problems/shortest-word-distance-iii/

题解:

也是Shortest word distance的follow up。这回两数可以一样。 在遍历的时候我们可以多写一个分支。 或者更简化的话可以把两个分支合并起来。

Time Complexity - O(n), Space Complexity - O(1)

public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        if(words == null || words.length == 0 || word1 == null || word2 == null)
            return 0;
        int minDistance = Integer.MAX_VALUE, word1Index = -1, word2Index = -1;
        boolean isWord1EqualsWord2 = word1.equals(word2);
        
        for(int i = 0; i < words.length; i++) {
            if(isWord1EqualsWord2) {
                if(words[i].equals(word1)) {
                    if(word1Index >= 0)
                        minDistance = Math.min(minDistance, i - word1Index);
                    word1Index = i;
                }
            } else {
                if(words[i].equals(word1))
                    word1Index = i;
                if(words[i].equals(word2))
                    word2Index = i;
                if(word1Index >= 0 && word2Index >= 0)
                    minDistance = Math.min(minDistance, Math.abs(word2Index - word1Index));    
            }
        }
        
        return minDistance;
    }
}

 

Reference:

https://leetcode.com/discuss/50360/my-concise-java-solution

https://leetcode.com/discuss/50715/12-16-lines-java-c

posted @ 2015-12-01 00:42  YRB  阅读(730)  评论(0编辑  收藏  举报