zoukankan      html  css  js  c++  java
  • Unique Word Abbreviation

    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)
    b) d|o|g                   --> d1g
       1  1
         1---5----0----5--8
    c) i|nternationalizatio|n  --> i18n
         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.
    
    Example: 
    Given dictionary = [ "deer", "door", "cake", "card" ]
    
    isUnique("dear") -> false
    isUnique("cart") -> true
    isUnique("cane") -> false
    isUnique("make") -> true

    要注意一种情况:isUnique("cake"), 应该是true. 虽然他的缩写在afterabbr出现,但是那就是他自己,没有别的跟他一样

    public class ValidWordAbbr {
        String[] dict;
        HashMap<String, Set<String>> afterAbbr;
    
        public ValidWordAbbr(String[] dictionary) {
            this.dict = dictionary;
            this.afterAbbr = new HashMap<String, Set<String>>();
            for (String item : dictionary) {
                String str = abbr(item);
                if (afterAbbr.containsKey(str)) {
                    afterAbbr.get(str).add(item);
                }
                else {
                    HashSet<String> set = new HashSet<String>();
                    set.add(item);
                    afterAbbr.put(str, set);
                }
            }
        }
    
        public boolean isUnique(String word) {
            String str = abbr(word);
            if (!afterAbbr.containsKey(str)) return true;
            else if (afterAbbr.containsKey(str) && afterAbbr.get(str).contains(word) && afterAbbr.get(str).size()==1) return true;
            return false;
        }
        
        public String abbr(String item) {
            if (item == null) return null;
            if (item.length() <= 2) return item;
            StringBuffer res = new StringBuffer();
            res.append(item.charAt(0));
            res.append(item.length()-2);
            res.append(item.charAt(item.length()-1));
            return res.toString();
        }
    }
    
    
    // Your ValidWordAbbr object will be instantiated and called as such:
    // ValidWordAbbr vwa = new ValidWordAbbr(dictionary);
    // vwa.isUnique("Word");
    // vwa.isUnique("anotherWord");
    

      

  • 相关阅读:
    phpstorm常用快捷键
    tp3.2.3运用phpexcel将excel文件导入mysql数据库
    TP3.2加载外部PHPexcel类,实现导入和导出
    Navicat常用快捷键
    thnkphp框架面试问题
    PHPSQL注入
    PHP4个载入语句的区别
    goflyway简单使用
    ubuntu16.04 HyperLedger Fabric 1.2.0 开发环境搭建
    DApp demo之pet-shop
  • 原文地址:https://www.cnblogs.com/apanda009/p/7791343.html
Copyright © 2011-2022 走看看