LeetCode Solutions

288. Unique Word Abbreviation

Time: Constructor: $O(|\texttt{dictionary}|)$, isUnique(word: str): $O(1)$

Space: $O(n)$

			

class ValidWordAbbr {
 public:
  ValidWordAbbr(vector<string>& dictionary) {
    dict = unordered_set(begin(dictionary), end(dictionary));

    for (const string& word : dict) {
      const string& abbr = getAbbr(word);
      abbrUnique[abbr] = !abbrUnique.count(abbr);
    }
  }

  bool isUnique(string word) {
    const string& abbr = getAbbr(word);
    return !abbrUnique.count(abbr) || abbrUnique[abbr] && dict.count(word);
  }

 private:
  unordered_set<string> dict;
  unordered_map<string, bool> abbrUnique;  // T := unique, F := not unique

  string getAbbr(const string& s) {
    const int n = s.length();
    if (n <= 2)
      return s;
    return s[0] + to_string(n - 2) + s.back();
  }
};
			

class ValidWordAbbr {
  public ValidWordAbbr(String[] dictionary) {
    dict = new HashSet<>(Arrays.asList(dictionary));

    for (final String word : dict) {
      final String abbr = getAbbr(word);
      abbrUnique.put(abbr, !abbrUnique.containsKey(abbr));
    }
  }

  public boolean isUnique(String word) {
    final String abbr = getAbbr(word);
    final Boolean hasAbbr = abbrUnique.get(abbr);
    return hasAbbr == null || hasAbbr && dict.contains(word);
  }

  private Set<String> dict;
  private Map<String, Boolean> abbrUnique = new HashMap<>(); // T := unique, F := not unique

  private String getAbbr(final String s) {
    final int n = s.length();
    if (n <= 2)
      return s;
    return s.charAt(0) + Integer.toString(n - 2) + s.charAt(n - 1);
  }
}
			

class ValidWordAbbr:
  def __init__(self, dictionary: List[str]):
    self.dict = set(dictionary)
    # T := unique, F := not unique
    self.abbrUnique = {}

    for word in self.dict:
      abbr = self._getAbbr(word)
      self.abbrUnique[abbr] = abbr not in self.abbrUnique

  def isUnique(self, word: str) -> bool:
    abbr = self._getAbbr(word)
    return abbr not in self.abbrUnique or self.abbrUnique[abbr] and word in self.dict

  def _getAbbr(self, s: str) -> str:
    n = len(s)
    if n <= 2:
      return s
    return s[0] + str(n - 2) + s[-1]