Skip to content

Commit 19c1978

Browse files
committed
2019-06-17
1 parent 4d45683 commit 19c1978

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class WordDistance(object):
2+
3+
def __init__(self, words):
4+
"""
5+
:type words: List[str]
6+
"""
7+
from collections import defaultdict
8+
self.words = words
9+
self.record = defaultdict(list)
10+
for i, word in enumerate(words):
11+
self.record[word].append(i)
12+
# print self.record
13+
def shortest(self, word1, word2):
14+
"""
15+
:type word1: str
16+
:type word2: str
17+
:rtype: int
18+
"""
19+
res = len(self.words)
20+
for pos1 in self.record[word1]:
21+
for pos2 in self.record[word2]:
22+
res = min(res, abs(pos1 - pos2))
23+
return res
24+
25+
26+
27+
# Your WordDistance object will be instantiated and called as such:
28+
# obj = WordDistance(words)
29+
# param_1 = obj.shortest(word1,word2)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution(object):
2+
def shortestWordDistance(self, words, word1, word2):
3+
"""
4+
:type words: List[str]
5+
:type word1: str
6+
:type word2: str
7+
:rtype: int
8+
"""
9+
res = len(words)
10+
11+
if word1 != word2:
12+
pos1, pos2 = -1, -1
13+
for i, word in enumerate(words):
14+
if word == word1:
15+
pos1 = i
16+
elif word == word2:
17+
pos2 = i
18+
if pos2 != -1 and pos1 != -1:
19+
res = min(res, abs(pos1 - pos2))
20+
else:
21+
pos = -1
22+
for i, word in enumerate(words):
23+
if word == word1:
24+
if pos != -1:
25+
# print i, pos
26+
res = min(res, i - pos)
27+
pos = i
28+
29+
return res

0 commit comments

Comments
 (0)