Python, beats 97%


  • 0
    class Solution(object):
        def shortestWordDistance(self, words, w1, w2):
            if w1 == w2:
                d = [i for i, w in enumerate(words) if w == w1]
                n, res = len(d), sys.maxsize
                for i in range(1, n):
                    res = min(res, d[i] - d[i - 1])
                return res
            res, d = sys.maxsize, {}
            for i, w in enumerate(words):
                if w == w1 and w2 in d:
                    res = min(res, i - d[w2])
                if w == w2 and w1 in d:
                    res = min(res, i - d[w1])
                if w == w1 or w == w2:
                    d[w] = i
            return res

  • 0

    Shorter.

    class Solution(object):
        def shortestWordDistance(self, words, word1, word2):
            minD = pos1 = pos2 = 2 * len(words)
            for i in xrange(0, len(words)):
                if words[i] == word1:
                    if word1 == word2:
                        pos2 = pos1
                    pos1 = i
                    minD = min(minD, abs(pos2 - pos1))
                elif words[i] == word2:
                    pos2 = i
                    minD = min(minD, abs(pos2 - pos1))
            return minD

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.