Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c2242cb

Browse files
Add medium problems
1 parent 2349dca commit c2242cb

File tree

2 files changed

+179
-0
lines changed

2 files changed

+179
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
# IMPLEMENT MAGIC DICTIONARY
3+
4+
Design a data structure that is initialized with a list of different words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
5+
6+
Implement the MagicDictionary class:
7+
8+
MagicDictionary() Initializes the object.
9+
void buildDict(String[] dictionary) Sets the data structure with an array of distinct strings dictionary.
10+
bool search(String searchWord) Returns true if you can change exactly one character in searchWord to match any string in the data structure, otherwise returns false.
11+
12+
13+
Example 1:
14+
15+
Input
16+
["MagicDictionary", "buildDict", "search", "search", "search", "search"]
17+
[[], [["hello", "leetcode"]], ["hello"], ["hhllo"], ["hell"], ["leetcoded"]]
18+
Output
19+
[null, null, false, true, false, false]
20+
21+
Explanation
22+
MagicDictionary magicDictionary = new MagicDictionary();
23+
magicDictionary.buildDict(["hello", "leetcode"]);
24+
magicDictionary.search("hello"); // return False
25+
magicDictionary.search("hhllo"); // We can change the second 'h' to 'e' to match "hello" so we return True
26+
magicDictionary.search("hell"); // return False
27+
magicDictionary.search("leetcoded"); // return False
28+
29+
30+
Constraints:
31+
32+
1 <= dictionary.length <= 100
33+
1 <= dictionary[i].length <= 100
34+
dictionary[i] consists of only lower-case English letters.
35+
All the strings in dictionary are distinct.
36+
1 <= searchWord.length <= 100
37+
searchWord consists of only lower-case English letters.
38+
buildDict will be called only once before search.
39+
At most 100 calls will be made to search.
40+
"""
41+
42+
class MagicDictionary:
43+
44+
def __init__(self):
45+
"""
46+
Initialize your data structure here.
47+
"""
48+
self.root = {}
49+
self.endSymbol = "*"
50+
51+
def buildDict(self, dictionary: List[str]) -> None:
52+
for word in dictionary:
53+
current = self.root
54+
for letter in word:
55+
if letter not in current:
56+
current[letter] = {}
57+
current = current[letter]
58+
current[self.endSymbol] = True
59+
60+
def search(self, searchWord: str) -> bool:
61+
return self.searchHelper(searchWord, 0, self.root, 0)
62+
63+
def searchHelper(self, word, index, trieNode, count):
64+
if index == len(word):
65+
return count == 1 and self.endSymbol in trieNode
66+
67+
letter = word[index]
68+
if letter not in trieNode and count == 1:
69+
return False
70+
71+
for node in trieNode:
72+
if node == self.endSymbol:
73+
continue
74+
nextCount = count if letter == node else count + 1
75+
if self.searchHelper(word, index + 1, trieNode[node], nextCount):
76+
return True
77+
78+
return False
79+
80+
# Your MagicDictionary object will be instantiated and called as such:
81+
# obj = MagicDictionary()
82+
# obj.buildDict(dictionary)
83+
# param_2 = obj.search(searchWord)

‎Leetcode/medium/replace-words.py‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
2+
# REPLACE WORDS
3+
4+
"""
5+
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root "an" is followed by the successor word "other", we can form a new word "another".
6+
7+
Given a dictionary consisting of many roots and a sentence consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length.
8+
9+
Return the sentence after the replacement.
10+
11+
12+
13+
Example 1:
14+
15+
Input: dictionary = ["cat","bat","rat"], sentence = "the cattle was rattled by the battery"
16+
Output: "the cat was rat by the bat"
17+
Example 2:
18+
19+
Input: dictionary = ["a","b","c"], sentence = "aadsfasf absbs bbab cadsfafs"
20+
Output: "a a b c"
21+
Example 3:
22+
23+
Input: dictionary = ["a", "aa", "aaa", "aaaa"], sentence = "a aa a aaaa aaa aaa aaa aaaaaa bbb baba ababa"
24+
Output: "a a a a a a a a bbb baba a"
25+
Example 4:
26+
27+
Input: dictionary = ["catt","cat","bat","rat"], sentence = "the cattle was rattled by the battery"
28+
Output: "the cat was rat by the bat"
29+
Example 5:
30+
31+
Input: dictionary = ["ac","ab"], sentence = "it is abnormal that this solution is accepted"
32+
Output: "it is ab that this solution is ac"
33+
34+
35+
Constraints:
36+
37+
1 <= dictionary.length <= 1000
38+
1 <= dictionary[i].length <= 100
39+
dictionary[i] consists of only lower-case letters.
40+
1 <= sentence.length <= 10^6
41+
sentence consists of only lower-case letters and spaces.
42+
The number of words in sentence is in the range [1, 1000]
43+
The length of each word in sentence is in the range [1, 1000]
44+
Each two consecutive words in sentence will be separated by exactly one space.
45+
sentence does not have leading or trailing spaces.
46+
"""
47+
48+
class Solution:
49+
def replaceWords(self, dictionary, sentence):
50+
trie = Trie(dictionary)
51+
sentence += " "
52+
sentenceList = list(sentence)
53+
finalList = []
54+
trieNode = trie.root
55+
index = 0
56+
while index < len(sentenceList):
57+
character = sentenceList[index]
58+
if trie.endSymbol in trieNode:
59+
finalList.append(" ")
60+
while sentenceList[index] != " ":
61+
index += 1
62+
trieNode = trie.root
63+
64+
elif character not in trieNode:
65+
print(character, "not")
66+
while index < len(sentenceList):
67+
finalList.append(sentenceList[index])
68+
if sentenceList[index] == " ":
69+
break
70+
index += 1
71+
72+
trieNode = trie.root
73+
74+
else:
75+
trieNode = trieNode[character]
76+
finalList.append(character)
77+
78+
index += 1
79+
80+
return "".join(finalList[:-1])
81+
82+
83+
class Trie:
84+
def __init__(self, words):
85+
self.root = {}
86+
self.endSymbol = "*"
87+
self.populateTrie(words)
88+
89+
def populateTrie(self, words):
90+
for word in words:
91+
current = self.root
92+
for letter in word:
93+
if letter not in current:
94+
current[letter] = {}
95+
current = current[letter]
96+
current[self.endSymbol] = word

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /