Skip to content

Unique word abbreviation

Tim_Gao edited this page Sep 16, 2016 · 2 revisions
  1. mistake make: I didn't quite get when we should return true.
    • when the abbreviation is not in dict
    • when the abbreviation is in dict the word should be the same as that in dict and there is no other words that have the same abbr
public class ValidWordAbbr {
    private HashMap<String, HashSet<String>> hm;
    public ValidWordAbbr(String[] dictionary) {
        hm = new HashMap<>();
        for (String word : dictionary){
            if (word.length() <=2 )
                continue;
            StringBuilder sb = new StringBuilder();
            sb.append(word.charAt(0)).append(word.length()-2).append(word.charAt(word.length()-1));
            if (!hm.containsKey(sb.toString())){
                hm.put(sb.toString(), new HashSet<String>());
            }
            hm.get(sb.toString()).add(word);
        }
    }

    public boolean isUnique(String word) {
        if (word.length() <=2 ){
            return true;
        }
        StringBuilder sb = new StringBuilder();
        sb.append(word.charAt(0)).append(word.length()-2).append(word.charAt(word.length()-1));
        if(hm.containsKey(sb.toString())){
            HashSet<String> words = hm.get(sb.toString());
            if (words.size() == 1 && words.contains(word)){
                return true;
            } else {
                return false;
            }
        } else {
            return true;
        }
    }
}


// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
// vwa.isUnique("Word");
// vwa.isUnique("anotherWord");

Clone this wiki locally