Implement a magic directory with buildDict, and search methods.



For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary.



For the method search, you'll be given a word, and judge whether if you modify exactly one character into another character in this word, the modified word is in the dictionary you just built.


Example 1:

Input: buildDict(["hello", "leetcode"]), Output: Null
Input: search("hello"), Output: False
Input: search("hhllo"), Output: True
Input: search("hell"), Output: False
Input: search("leetcoded"), Output: False



Note:

You may assume that all the inputs are consist of lowercase letters a-z.
For contest purpose, the test data is rather small by now. You could think about highly efficient algorithm after the contest.
Please remember to RESET your class variables declared in class MagicDictionary, as static/class variables are persisted across multiple test cases. Please see here for more details.

Difficulty: MEDIUM_HARD
Tags: String algorithms

Data structures
Skill types: Data structures

Starter code:
class MagicDictionary:
    def __init__(self):
        """
        Initialize your data structure here.
        """
    def buildDict(self, dictionary: List[str]) -> None:
    def search(self, searchWord: str) -> bool:
# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)

Solutions:
class MagicDictionary:

	def __init__(self):
		self.l = []

	def buildDict(self, dict):
		self.l = dict

	def search(self, word):

		def diffnumber(a, b):
			count = 0
			for i in range(len(a)):
				if a[i] != b[i]:
					count += 1
			return count
		for x in self.l:
			if len(x) == len(word) and diffnumber(x, word) == 1:
				return True
		return False


class MagicDictionary:

	def __init__(self):
		self.dict1 = {}

	def buildDict(self, dict):
		for i in dict:
			self.dict1[len(i)] = self.dict1.get(len(i), []) + [i]

	def search(self, word):
		for i in self.dict1.get(len(word), []):
			count = 0
			for j in range(len(word)):
				if i[j] != word[j]:
					count += 1
			if count == 1:
				return True
		return False


class MagicDictionary:

	def __init__(self):
		self.hsh = collections.defaultdict(list)

	def buildDict(self, dict):
		for word in dict:
			self.hsh[len(word)].append(word)

	def search(self, word):
		return any((sum((x != y for (x, y) in zip(word, candidate))) == 1 for candidate in self.hsh[len(word)]))


class MagicDictionary:

	def __init__(self):
		self.tier = [None] * 27

	def buildDict(self, dict):
		for word in dict:
			p = self.tier
			for c in word:
				t = ord(c) - ord('a')
				if not p[t]:
					p[t] = [None] * 27
				p = p[t]
			p[26] = 1

	def search(self, word):

		def func(w):
			p = self.tier
			for c in w:
				t = ord(c) - ord('a')
				if not p[t]:
					return False
				p = p[t]
			return p[26] == 1
		pool = 'abcdefghijklmnopqrstuvwxyz'
		for i in range(len(word)):
			for cc in pool:
				if cc != word[i]:
					tt = word[:i] + '%c' % cc + word[i + 1:]
					if func(tt):
						return True
		return False


class MagicDictionary:

	def __init__(self):
		self.word_set = {}
		self.word_origin = set([])

	def candidate(self, word):
		result = []
		for i in range(len(word)):
			result.append(word[0:i] + '*' + word[i + 1:])
		return result

	def buildDict(self, dict):
		self.word_set = {}
		self.word_origin = set(dict)
		for item in dict:
			for cand in self.candidate(item):
				self.word_set[cand] = self.word_set.get(cand, 0) + 1

	def search(self, word):
		for cand in self.candidate(word):
			if self.word_set.get(cand, 0) > 1 or (self.word_set.get(cand, 0) == 1 and word not in self.word_origin):
				return True
		return False


class MagicDictionary:

	def __init__(self):
		self.trie_root = dict()
		self.original_words = None

	def buildDict(self, dictionary):

		def add_word(trie_root, word):
			p = trie_root
			for character in word:
				if character not in p:
					p[character] = dict()
				p = p[character]
			p['\x00'] = True
		self.original_words = set(dictionary)

	def search(self, word):
		charset = 'abcdefghijklmnopqrstuvwxyz'
		for (index, character) in enumerate(word):
			for replaced_character in charset:
				if character != replaced_character:
					if word[:index] + replaced_character + word[index + 1:] in self.original_words:
						return True
		return False


class MagicDictionary:

	def __init__(self):
		self.d = None

	def buildDict(self, dict):
		d = set()
		for word in dict:
			d.add(word)
		self.d = d

	def search(self, word):
		if not word:
			return

		def editDistDP(s1, s2):
			(m, n) = (len(s1), len(s2))
			dp = [[0 for x in range(n + 1)] for x in range(m + 1)]
			for i in range(m + 1):
				for j in range(n + 1):
					if i == 0:
						dp[i][j] = j
					elif j == 0:
						dp[i][j] = i
					elif s1[i - 1] == s2[j - 1]:
						dp[i][j] = dp[i - 1][j - 1]
					else:
						dp[i][j] = 1 + dp[i - 1][j - 1]
			return dp[m][n]
		ans = False
		for dic in self.d:
			if len(dic) != len(word):
				continue
			ans = ans or editDistDP(dic, word) == 1
		return ans


class MagicDictionary:

	def __init__(self):
		self.dict = set()

	def buildDict(self, dict):
		for word in dict:
			self.dict.add(word)

	def search(self, word):
		letters = string.ascii_lowercase
		for i in range(len(word)):
			for letter in letters:
				if letter != word[i]:
					if word[:i] + letter + word[i + 1:] in self.dict:
						return True
		return False


class MagicDictionary:

	def __init__(self):
		self.magic_dict = set()

	def buildDict(self, words):
		for word in words:
			for i in range(len(word)):
				for char in range(26):
					char = chr(ord('a') + char)
					if char != word[i]:
						self.magic_dict.add(word[:i] + char + word[i + 1:])

	def search(self, word):
		return word in self.magic_dict


class MagicDictionary:

	def __init__(self):
		self.dict = collections.defaultdict(list)

	def buildDict(self, dict):
		for word in dict:
			self.dict[len(word)].append(word)

	def search(self, word):
		n = len(word)
		print((word, self.dict[n]))
		for item in self.dict[n]:
			count = 0
			for i in range(n):
				if count > 1:
					continue
				if item[i] != word[i]:
					count += 1
			if count == 1:
				return True
		return False