Simple Java Solution (190 ms, Beats 99.31% Java Submissions) (explanation given)


  • 0
    A

    The idea is to store the abbreviation mapped to the string in a hashmap.
    If two strings in the dictionary produces same abbreviations, then we map this abbreviation to empty string.

    Then, in inUnique mehod just check the string associated with the word's abbreviation in the map.
    We have two cases

    1. Word's abbreviation does not exist in map, in that cases return true..as we found unique abbreviation

    2. Word's abbreviation does exist in map,

    then again we have two cases

    a) String associated with the Word's abbreviation matches with Word, then return true.
    Because, if we came this far means Words length is greater than 2 and if mapped string contains value other than empty string means that, this string has unique abbreviations in dictionary..means we can not have "cake" and "cane" at the same time..if we had we would map "c2e" to "" in map

    b)String associated with the Word's abbreviation does not matches with Word, then it will either be "" string or any other string with same abbreviations as of Word, in both cases we will return false

    class ValidWordAbbr {
        Map<String,String> map;
        StringBuilder sb;
        public ValidWordAbbr(String[] dictionary) {
            map = new HashMap<>();
            for(String str:dictionary){
                int len = str.length();
                if(len < 3)
                    continue;
                sb = new StringBuilder("");
                sb.append(str.charAt(0)).append(len-2).append(str.charAt(len-1));
                String temp = sb.toString();
                if(map.containsKey(temp)){
                    map.put(temp,"");
                }else{
                    map.put(temp,str);
                }
            }
        }
        
        public boolean isUnique(String word) {
            int len = word.length();
            if(len < 3)
                return true;
            
            String temp = "" + word.charAt(0) + (len-2) + word.charAt(len-1);
            return !map.containsKey(temp) || map.get(temp).equals(word);
        }
    }
    
    /**
     * Your ValidWordAbbr object will be instantiated and called as such:
     * ValidWordAbbr obj = new ValidWordAbbr(dictionary);
     * boolean param_1 = obj.isUnique(word);
     */
    

Log in to reply
 

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