Ac solution code


  • 0

    The following two situations can validate the word W's abbreviation is unique:

    1. W is not in the dictionary;

    2. W is in the dictionary, and NO OTHER word in the dictionary having the same abbreviation as W's.

      public class ValidWordAbbr {
      private Map<String, String>map = new HashMap<String, String>();

      public ValidWordAbbr(String[] dictionary) {
      	for (String s : dictionary) {
      		String key = getAbbr(s);
      		if (!key.equals("")) {// Only save valid abbreviations
       			if (map.containsKey(key))
       				map.put(key, "");
       			else
       				map.put(key, s);
      		} 
      	}
       }	    	
       public boolean isUnique(String word) {
       	if (word == null) 
       		return false;
       	String key = getAbbr(word);
       	return !map.containsKey(key) || map.get(key).equals(word);
       }            
      private String getAbbr(String s) {
      	if (s == null || s.length() <= 2)
      		return "";
      	return s.charAt(0) + String.valueOf(s.length()-2) + s.charAt(s.length()-1);
      }
      

      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.