#288
Medium Algorithms Unique word abbreviation
Array Hash Table String Design
27.5% acceptance
Mar 31, 2026
219
1856
The abbreviation of a word is a concatenation of its first letter, the number of characters between the first and last letter, and its last letter. If a word has only two characters, then it is an abbreviation of itself.
For example:
dog --> d1g because there is one letter between the first letter 'd' and the last letter 'g'.
internationalization --> i18n because there are 18 letters between the first letter 'i' and the last letter 'n'.
it --> it because any word with only two characters is an abbreviation of itself.
Implement the ValidWordAbbr class:
ValidWordAbbr(String[] dictionary) Initializes the object with a dictionary of words.
boolean isUnique(string word) Returns true if either of the following conditions are met (otherwise returns false):
There is no word in dictionary whose abbreviation is equal to word's abbreviation.
For any word in dictionary whose abbreviation is equal to word's abbreviation, that word and word are the same.
Solution
Rust
Time O(2^n)
Space O(n)
use std::collections::{HashMap, HashSet};
struct ValidWordAbbr {
map: HashMap<String, HashSet<String>>,
}
impl ValidWordAbbr {
fn new(dictionary: Vec<String>) -> Self {
let mut map: HashMap<String, HashSet<String>> = HashMap::new();
for word in dictionary {
let abbr = Self::abbreviate(&word);
map.entry(abbr).or_default().insert(word);
}
ValidWordAbbr { map }
}
fn abbreviate(word: &str) -> String {
let n = word.len();
if n <= 2 {
return word.to_string();
}
let bytes = word.as_bytes();
format!("{}{}{}", bytes[0] as char, n - 2, bytes[n - 1] as char)
}
fn is_unique(&self, word: String) -> bool {
let abbr = Self::abbreviate(&word);
match self.map.get(&abbr) {
None => true,
Some(set) => set.len() == 1 && set.contains(&word),
}
}
}
// ValidWordAbbr usage:
// let obj = ValidWordAbbr::new(dictionary);
// let ret_1: bool = obj.is_unique(word);