Leetcode 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 word1 does not equal to word2, and word1 and word2 are both in the list.


解题思路:

双指针,一个指着word1的index, 一个指着word2的index,求它俩差值的最小值。Complexity: O(words.length)


 Java code

public int shortestDistance(String[] words, String word1, String word2) {
        int p1 = -1, p2 = -1, distance = Integer.MAX_VALUE;
       
        for(int i = 0; i< words.length; i++){
            if(word1.equals(words[i])) {
                p1 = i;
            }
            if(word2.equals(words[i])) {
                p2 = i;
            }
            if(p1 != -1 && p2 != -1) {
                distance = Math.min(distance, Math.abs(p1-p2));
            }
        }
        return distance;
    }

Reference:

1. https://leetcode.com/discuss/50234/ac-java-clean-solution

 

posted @ 2015-09-23 01:13  茜茜的技术空间  阅读(289)  评论(0编辑  收藏  举报