|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.HashSet; |
| 4 | +import java.util.Set; |
| 5 | + |
| 6 | +/** |
| 7 | + * 676. Implement Magic Dictionary |
| 8 | + * Implement a magic directory with buildDict, and search methods. |
| 9 | + * For the method buildDict, you'll be given a list of non-repetitive words to build a dictionary. |
| 10 | + * For the method search, you'll be given a word, |
| 11 | + * and judge whether if you modify exactly one character into another character in this word, |
| 12 | + * the modified word is in the dictionary you just built. |
| 13 | +
|
| 14 | + Example 1: |
| 15 | +
|
| 16 | + Input: buildDict(["hello", "leetcode"]), Output: Null |
| 17 | + Input: search("hello"), Output: False |
| 18 | + Input: search("hhllo"), Output: True |
| 19 | + Input: search("hell"), Output: False |
| 20 | + Input: search("leetcoded"), Output: False |
| 21 | +
|
| 22 | + Note: |
| 23 | +
|
| 24 | + You may assume that all the inputs are consist of lowercase letters a-z. |
| 25 | + For contest purpose, the test data is rather small by now. |
| 26 | + You could think about highly efficient algorithm after the contest. |
| 27 | + Please remember to RESET your class variables declared in class MagicDictionary, |
| 28 | + as static/class variables are persisted across multiple test cases. Please see here for more details. |
| 29 | +
|
| 30 | + */ |
| 31 | +public class _676 { |
| 32 | + |
| 33 | + public static class Solution1 { |
| 34 | + public static class MagicDictionary { |
| 35 | + |
| 36 | + Set<String> wordSet; |
| 37 | + |
| 38 | + /** |
| 39 | + * Initialize your data structure here. |
| 40 | + */ |
| 41 | + public MagicDictionary() { |
| 42 | + wordSet = new HashSet<>(); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Build a dictionary through a list of words |
| 47 | + */ |
| 48 | + public void buildDict(String[] dict) { |
| 49 | + for (String word : dict) { |
| 50 | + wordSet.add(word); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Returns if there is any word in the trie that equals to the given word after modifying exactly one character |
| 56 | + */ |
| 57 | + public boolean search(String word) { |
| 58 | + for (String candidate : wordSet) { |
| 59 | + if (modifyOneChar(word, candidate)) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + private boolean modifyOneChar(String word, String candidate) { |
| 67 | + if (word.length() != candidate.length()) { |
| 68 | + return false; |
| 69 | + } |
| 70 | + int diff = 0; |
| 71 | + for (int i = 0; i < word.length(); i++) { |
| 72 | + if (word.charAt(i) != candidate.charAt(i)) { |
| 73 | + diff++; |
| 74 | + } |
| 75 | + if (diff > 1) { |
| 76 | + return false; |
| 77 | + } |
| 78 | + } |
| 79 | + return diff == 1; |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments