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");
    

      

  • 相关阅读:
    编写安全有效的 C# 代码
    模式匹配
    C#新特性
    转 C# .NET4.0 混合模式程序集异常
    win7 64位系统 注册 ocx控件
    TIFF图像文件格式详解
    GDALOGR读取数据示例 C#版本
    使用gdal C#封装库读取DEM数据
    编译C#环境下GDAL(支持HDF4、NetCDF)
    UML类图符号 各种关系说明以及举例
  • 原文地址:https://www.cnblogs.com/apanda009/p/7791343.html
Copyright © 2011-2022 走看看