Leetcode

Replace Words

  • Time:Time:
  • Space:Space:

C++

struct TrieNode {
  vector<TrieNode*> children;
  const string* word = nullptr;
  TrieNode() : children(26) {}
  ~TrieNode() {
    for (TrieNode* child : children)
      delete (child);
  }
};

class Solution {
 public:
  string replaceWords(vector<string>& dict, string sentence) {
    for (const string& word : dict)
      insert(word);

    string ans;
    istringstream iss(sentence);

    for (string s; iss >> s;)
      ans += search(s) + ' ';
    ans.pop_back();

    return ans;
  }

 private:
  TrieNode root;

  void insert(const string& word) {
    TrieNode* node = &root;
    for (const char c : word) {
      if (!node->children[c - 'a'])
        node->children[c - 'a'] = new TrieNode;
      node = node->children[c - 'a'];
    }
    node->word = &word;
  }

  string search(const string& word) {
    TrieNode* node = &root;
    for (const char c : word) {
      if (node->word)
        return *node->word;
      if (!node->children[c - 'a'])
        return word;
      node = node->children[c - 'a'];
    }
    return word;
  }
};

JAVA

class Solution {
  public String replaceWords(List<String> dict, String sentence) {
    String ans = "";

    for (final String word : dict)
      insert(word);

    final String[] words = sentence.split(" ");
    for (final String word : words)
      ans += ' ' + search(word);

    return ans.substring(1);
  }

  private class TrieNode {
    private TrieNode[] children = new TrieNode[26];
    private String word;
  }

  private TrieNode root = new TrieNode();

  private void insert(final String word) {
    TrieNode node = root;
    for (char c : word.toCharArray()) {
      int index = c - 'a';
      if (node.children[index] == null)
        node.children[index] = new TrieNode();
      node = node.children[index];
    }
    node.word = word;
  }

  private String search(final String word) {
    TrieNode node = root;
    for (char c : word.toCharArray()) {
      if (node.word != null)
        return node.word;
      int index = c - 'a';
      if (node.children[index] == null)
        return word;
      node = node.children[index];
    }
    return word;
  }
}

Python

class Solution:
  def __init__(self):
    self.root = {}

  def insert(self, word: str) -> None:
    node = self.root
    for c in word:
      if c not in node:
        node[c] = {}
      node = node[c]
    node['word'] = word

  def search(self, word: str) -> str:
    node = self.root
    for c in word:
      if 'word' in node:
        return node['word']
      if c not in node:
        return word
      node = node[c]
    return word

  def replaceWords(self, dict: List[str], sentence: str) -> str:
    for word in dict:
      self.insert(word)

    words = sentence.split(' ')
    return ' '.join([self.search(word) for word in words])