天天看點

[LeetCode] Implement Magic Dictionary 實作神奇字典

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:

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.

解法一:

<a>class MagicDictionary {</a>

下面這種解法實際上是用到了字首樹中的search的思路,但是我們又沒有整個用到prefix tree,部落客感覺那樣寫法略複雜,其實我們隻需要借鑒一下search方法就行了。我們首先将所有的單詞都放到一個集合中,然後在search函數中,我們周遊要搜尋的單詞的每個字元,然後把每個字元都用a-z中的字元替換一下,形成一個新詞,當然遇到本身要跳過。然後在集合中看是否存在,存在的話就傳回true。記得換完一圈字元後要換回去,不然就不滿足隻改變一個字元的條件了,參見代碼如下:

解法二:

參考資料:

<a href="https://discuss.leetcode.com/topic/103004/c-clean-code">https://discuss.leetcode.com/topic/103004/c-clean-code</a>

<a href="https://discuss.leetcode.com/topic/102992/easy-14-lines-java-solution-hashmap">https://discuss.leetcode.com/topic/102992/easy-14-lines-java-solution-hashmap</a>

,如需轉載請自行聯系原部落客。