LeetCode Solutions

648. Replace Words

Time:

Space:

			

struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  const string* word = nullptr;
  TrieNode() : children(26) {}
};

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:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  void insert(const string& word) {
    shared_ptr<TrieNode> node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (node->children[i] == nullptr)
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
    }
    node->word = &word;
  }

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

class Solution {
  public String replaceWords(List<String> dict, String sentence) {
    StringBuilder sb = new StringBuilder();

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

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

    return sb.substring(1).toString();
  }

  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()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.word = word;
  }

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

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])