Add and Search Word

211. Add and Search Word - Data structure design

LintCode-473.Add and Search Word

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

class TrieNode {
  private var children: [TrieNode?] = []
  public var isEnd = false
  
  init() {
    self.children = Array(repeating: nil, count: 26)
    self.isEnd = false
  }
  
  func put(_ c: Character, _ node: TrieNode) {
    let val = Int(c.unicodeScalars.first!.value - UnicodeScalar("a").value)
    children[val] = node
  }
  
  func get(_ c: Character) -> TrieNode? {
    return children[Int(c.unicodeScalars.first!.value - UnicodeScalar("a").value)]
  }
  
  func getChildren() -> [TrieNode?] {
    return children  
  }
}

class WordDictionary {
   private var root: TrieNode

    /** Initialize your data structure here. */
    init() {
        self.root = TrieNode()
    }
    
    /** Adds a word into the data structure. */
    func addWord(_ word: String) {
        var node = root
    
        for c in word {
            if let n = node.get(c) {
                node = n
            } else {
                let n = TrieNode()
                node.put(c, n)
        
                node = n
            }
        }
    
        node.isEnd = true
    }
    
    /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    func search(_ word: String) -> Bool {
        return search(word, root, 0)
    }
    
    func search(_ word: String, _ node: TrieNode?, _ i: Int) -> Bool {
        guard let node = node else {
            return false
        }
    
        if i == word.count {
            return node.isEnd
        }
    
        let c = word[word.index(word.startIndex, offsetBy: i)]
        if c == "." {
            for n in node.getChildren() where n != nil {
                if search(word, n, i + 1) {
                    return true
                }
            }
      
            return false
        } else {      
            return search(word, node.get(c), i + 1)
        }
    }
}

/**
 * Your WordDictionary object will be instantiated and called as such:
 * let obj = WordDictionary()
 * obj.addWord(word)
 * let ret_2: Bool = obj.search(word)
 */

let dict = WordDictionary()
dict.addWord("bad")
dict.addWord("dad")
dict.addWord("mad")
print(dict.search("pad"))
print(dict.search("bad"))
print(dict.search(".ad"))
print(dict.search("b.."))
class TrieNode {
    private TrieNode[] children;
    private boolean isEnd;

    public TrieNode() {
        children = new TrieNode[26];
    }

    public boolean containsKey(char c) {
        return children[c -'a'] != null;
    }
    
    public TrieNode get(char c) {
        return children[c -'a'];
    }
    
    public void put(char c, TrieNode node) {
        children[c -'a'] = node;
    }
    
    public void setEnd() {
        isEnd = true;
    }
    
    public boolean isEnd() {
        return isEnd;
    }
    
    public TrieNode[] children() {
        return children;
    }
}

public class WordDictionary {
    private TrieNode root;
    
    public WordDictionary() {
        root = new TrieNode();
    }

    // Adds a word into the data structure.
    public void addWord(String word) {
        TrieNode node = root;
        
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            
            if (!node.containsKey(c)) {
                node.put(c, new TrieNode());    
            }
            
            node = node.get(c);
        }
        
        node.setEnd();
    }
    
    private boolean search(TrieNode node, String word, int index) {
        if (node == null) {
            return false;
        } else if (index == word.length()) {
            return node.isEnd();
        }

        char c = word.charAt(index);

        if (c == '.') {
            for (TrieNode n : node.children()) {
                if (n != null) {
                    if(search (n, word, index + 1)) {
                        return true;
                    }
                }
            }

            return false;
        } else {
            TrieNode n = node.get(c);
            
            return search(n, word, index + 1);
        }
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    public boolean search(String word) {
        return search(root, word, 0);
    }
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

Hope this helps,
Michael

DigitalOcean Referral Badge