Skip to content

Commit 13327c4

Browse files
Create Replace_words.py
1 parent 6832d7d commit 13327c4

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: Replace_words.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution_0:
2+
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
3+
s = set(dictionary)
4+
sentence = sentence.split()
5+
for j, w in enumerate(sentence):
6+
for i in range(1, len(w)):
7+
if w[:i] in s:
8+
sentence[j] = w[:i]
9+
break
10+
return " ".join(sentence)
11+
12+
class Solution_1:
13+
def replaceWords(self, roots, sentence):
14+
rootset = set(roots)
15+
16+
def replace(word):
17+
for i in range(1, len(word)):
18+
if word[:i] in rootset:
19+
return word[:i]
20+
return word
21+
22+
return " ".join(map(replace, sentence.split()))
23+
24+
class Solution:
25+
def replaceWords(self, dictionary: List[str], sentence: str) -> str:
26+
d = {w: len(w) for w in dictionary}
27+
mi, ma = min(d.values()), max(d.values())
28+
wrds = sentence.split()
29+
res = []
30+
for w in wrds:
31+
c = w
32+
for i in range(mi, min(ma, len(w)) + 1):
33+
ss = w[:i]
34+
if ss in d:
35+
c = ss
36+
break
37+
res.append(c)
38+
return " ".join(res)

0 commit comments

Comments
 (0)