美文网首页
Unique Word Abbreviation

Unique Word Abbreviation

作者: BLUE_fdf9 | 来源:发表于2018-09-26 11:06 被阅读0次

    题目
    An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations:

    a) it --> it (no abbreviation)

     1
     ↓
    

    b) d|o|g --> d1g

              1    1  1
     1---5----0----5--8
     ↓   ↓    ↓    ↓  ↓    
    

    c) i|nternationalizatio|n --> i18n

              1
     1---5----0
     ↓   ↓    ↓
    

    d) l|ocalizatio|n --> l10n
    Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.

    答案

    class ValidWordAbbr {
        Map<String, Integer> map = new HashMap<>();
        Set<String> dict = new HashSet<>();
        
        public String make_abbr(String s) {
            if(s.length() <= 2) return s;
            else return s.charAt(0) + Integer.toString(s.length() - 2) + s.charAt(s.length() - 1);
        }
        
        public ValidWordAbbr(String[] dictionary) {
            for(String s : dictionary) {
                if(!dict.contains(s)) {
                    String abbr = make_abbr(s);
                    map.putIfAbsent(abbr, 0);
                    int freq = map.get(abbr);
                    map.put(abbr, freq + 1);
                    dict.add(s);                
                }
    
            }
        }
        
        public boolean isUnique(String word) {
            Integer freq = map.get(make_abbr(word));
            if(freq == null) {
                return true;
            }
            else {
                return (freq == 1 && dict.contains(word));
            }
        }
    }
    
    /**
     * Your ValidWordAbbr object will be instantiated and called as such:
     * ValidWordAbbr obj = new ValidWordAbbr(dictionary);
     * boolean param_1 = obj.isUnique(word);
     */
    

    相关文章

      网友评论

          本文标题:Unique Word Abbreviation

          本文链接:https://www.haomeiwen.com/subject/wnckoftx.html