|
| 1 | +""" |
| 2 | +ํ์ด๋ฅผ ๋ณด๊ณ ๊ณต๋ถํ์ต๋๋ค. |
| 3 | +
|
| 4 | +Solution: |
| 5 | + set์ ์ด์ฉ, |
| 6 | + 1) addWord ์์ add |
| 7 | + 2) search ์์ .์ ํฌํจํ ๋ชจ๋ ๊ธ์๊ฐ ๋์ผํ ๋จ์ด๊ฐ ์๋์ง ํ์ธ |
| 8 | +
|
| 9 | +search |
| 10 | + Time: O(n * w) |
| 11 | + Space: O(1) |
| 12 | +""" |
| 13 | + |
| 14 | + |
| 15 | +class WordDictionary: |
| 16 | + |
| 17 | + def __init__(self): |
| 18 | + self.root = set() |
| 19 | + |
| 20 | + def addWord(self, word: str) -> None: |
| 21 | + self.root.add(word) |
| 22 | + |
| 23 | + def search(self, word: str) -> bool: |
| 24 | + for candidate in self.root: |
| 25 | + if len(candidate) != len(word): |
| 26 | + continue |
| 27 | + if all(w == c or w == "." for w, c in zip(word, candidate)): |
| 28 | + return True |
| 29 | + return False |
| 30 | + |
| 31 | + |
| 32 | +""" |
| 33 | +ํ์ด๋ฅผ ๋ณด๊ณ ๊ณต๋ถํ์ต๋๋ค. |
| 34 | +
|
| 35 | +Solution: Trie - ๋ฌ๋ ์ ์ฝ๋ |
| 36 | +""" |
| 37 | + |
| 38 | + |
| 39 | +class WordDictionary: |
| 40 | + |
| 41 | + def __init__(self): |
| 42 | + self.root = {"$": True} |
| 43 | + |
| 44 | + def addWord(self, word: str) -> None: |
| 45 | + node = self.root |
| 46 | + for ch in word: |
| 47 | + if ch not in node: |
| 48 | + node[ch] = {"$": False} |
| 49 | + node = node[ch] |
| 50 | + node["$"] = True |
| 51 | + |
| 52 | + def search(self, word: str) -> bool: |
| 53 | + def dfs(node, idx): |
| 54 | + if idx == len(word): |
| 55 | + return node["$"] |
| 56 | + |
| 57 | + ch = word[idx] |
| 58 | + if ch in node: |
| 59 | + return dfs(node[ch], idx + 1) |
| 60 | + if ch == ".": |
| 61 | + if any(dfs(node[k], idx + 1) for k in node if k != "$"): |
| 62 | + return True |
| 63 | + return False |
| 64 | + |
| 65 | + return dfs(self.root, 0) |
| 66 | + |
| 67 | + |
| 68 | +""" |
| 69 | +ํ์ด๋ฅผ ๋ณด๊ณ ๊ณต๋ถํ์ต๋๋ค. |
| 70 | +
|
| 71 | +Solution: Trie with TrieNode - NeetCode |
| 72 | +""" |
| 73 | + |
| 74 | + |
| 75 | +class TrieNode: |
| 76 | + def __init__(self): |
| 77 | + self.children = {} # a: TrieNode |
| 78 | + self.word = False |
| 79 | + |
| 80 | + |
| 81 | +class WordDictionary: |
| 82 | + |
| 83 | + def __init__(self): |
| 84 | + self.root = TrieNode() |
| 85 | + |
| 86 | + def addWord(self, word: str) -> None: |
| 87 | + cur = self.root |
| 88 | + |
| 89 | + for c in word: |
| 90 | + if c not in cur.children: |
| 91 | + cur.children[c] = TrieNode() |
| 92 | + cur = cur.children[c] |
| 93 | + cur.word = True |
| 94 | + |
| 95 | + def search(self, word: str) -> bool: |
| 96 | + def dfs(j, root): |
| 97 | + cur = root |
| 98 | + for i in range(j, len(word)): |
| 99 | + c = word[i] |
| 100 | + |
| 101 | + if c == ".": |
| 102 | + for child in cur.children.values(): |
| 103 | + if dfs(i + 1, child): |
| 104 | + return True |
| 105 | + return False |
| 106 | + else: |
| 107 | + if c not in cur.children: |
| 108 | + return False |
| 109 | + cur = cur.children[c] |
| 110 | + return cur.word |
| 111 | + |
| 112 | + return dfs(0, self.root) |
0 commit comments