首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode 288. 单词的唯一缩写(哈希)

LeetCode 288. 单词的唯一缩写(哈希)

作者头像
Michael阿明
发布2020-07-13 15:08:39
发布2020-07-13 15:08:39
9440
举报

1. 题目

一个单词的缩写需要遵循 <起始字母><中间字母数><结尾字母> 这样的格式。

以下是一些单词缩写的范例:

代码语言:javascript
复制
a) it                      --> it    (没有缩写)

     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

假设你有一个字典和一个单词,请你判断该单词的缩写在这本字典中是否唯一。 若单词的缩写在字典中没有任何 其他 单词与其缩写相同,则被称为单词的唯一缩写。

代码语言:javascript
复制
示例:
给定 dictionary = [ "deer", "door", "cake", "card" ]
isUnique("dear") -> false
isUnique("cart") -> true
isUnique("cane") -> false
isUnique("make") -> true

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/unique-word-abbreviation 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2. 解题

容易错的例子

代码语言:javascript
复制
[[["hello"]],["hello"]]			[null,true]
[[["a","a"]],["a"]]				[null,true]
  • 长度小于等于2的直接true
  • 对转换后的 key 计数
代码语言:javascript
复制
class ValidWordAbbr {
	unordered_map<string, int> m;
    unordered_set<string> dict;
	string key;
public:
    ValidWordAbbr(vector<string>& dictionary) {
    	for(auto& d : dictionary)
    	{
            if(d.size()<=2)
                continue;
            m[getkey(d)]++;
            dict.insert(d);
        }
    }
    
    bool isUnique(string word) {
        if(word.size() <= 2)
            return true;
    	key = getkey(word);
    	if((dict.count(word) && (m[key] == 1)) || m.find(key) == m.end())
    		return true;
    	else
    		return false;
    }
    string getkey(string& word)
    {
    	key = word[0]+to_string(word.size()-2)+word[word.size()-1];
    	return key;
    }
};

296 ms 48.2 MB

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/07/02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档