Skip to content

288. Unique Word Abbreviation 👎

  • Time:
    • Constructor: $O(|\texttt{dictionary}|)$
    • isUnique(word: str): $O(1)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class ValidWordAbbr {
 public:
  ValidWordAbbr(vector<string>& dictionary) {
    dict = unordered_set(dictionary.begin(), dictionary.end());

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

  bool isUnique(string word) {
    const string& abbr = getAbbr(word);
    return !abbrUnique.contains(abbr) ||
           abbrUnique[abbr] && dict.contains(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();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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]