Leetcode

Longest Word With All Prefixes

  • Time:Time:
  • Space:Space:

C++

struct TrieNode {
  vector<TrieNode*> children;
  bool isWord = false;
  TrieNode() : children(26) {}
  ~TrieNode() {
    for (TrieNode* child : children)
      delete child;
  }
};

class Solution {
 public:
  string longestWord(vector<string>& words) {
    string ans;

    for (const string& word : words)
      insert(word);

    for (const string& word : words) {
      if (!allPrefixed(word))
        continue;
      if (ans.length() < word.length() ||
          (ans.length() == word.length() && ans > word))
        ans = word;
    }

    return ans;
  }

 private:
  TrieNode root;

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

  bool allPrefixed(const string& word) {
    TrieNode* node = &root;
    for (const char c : word) {
      const int i = c - 'a';
      node = node->children[i];
      if (!node->isWord)
        return false;
    }
    return true;
  }
};

JAVA

class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public boolean isWord = false;
}

class Solution {
  public String longestWord(String[] words) {
    String ans = "";

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

    for (final String word : words) {
      if (!allPrefixed(word))
        continue;
      if (ans.length() < word.length() ||
          (ans.length() == word.length() && ans.compareTo(word) > 0))
        ans = word;
    }

    return ans;
  }

  private TrieNode root = new TrieNode();

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

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

Python

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

  def longestWord(self, words: List[str]) -> str:
    ans = ''

    for word in words:
      self.insert(word)

    for word in words:
      if not self.allPrefixed(word):
        continue
      if len(ans) < len(word) or (len(ans) == len(word) and ans > word):
        ans = word

    return ans

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

  def allPrefixed(self, word: str) -> bool:
    node = self.root
    for c in word:
      node = node[c]
      if 'isWord' not in node:
        return False
    return True