您的位置:首页 > 产品设计 > UI/UE

[LeetCode288]Unique Word Abbreviation

2015-11-26 13:17 411 查看
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.

Example:
Given dictionary = [ "deer", "door", "cake", "card" ]

isUnique("dear") -> false
isUnique("cart") -> true
isUnique("cane") -> false
isUnique("make") -> true
Hide Company Tags Google
Hide Tags Hash Table Design
Hide Similar Problems (E) Two Sum III - Data structure design


刚开始觉得就是找出abbreviation当key 把自己加到hashtable里,然后看每个key的size是不是1就可以判断是不是unique word了,但是发现了这句话
A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.
就比如a,a,a自己的缩写和自己一样,也算unique的。

有两种structure可以用,vector 和set。

class ValidWordAbbr {
public:
ValidWordAbbr(vector<string> &dictionary) {
for(string s : dictionary){
mp[abbrivate(s)].push_back(s);
}
}
string abbrivate(string s){
int len = s.size();
return len<=2 ? s : s[0] + to_string(len-2) + s[len-1];
}
bool isUnique(string word) {
for(string s : mp[abbrivate(word)]){
if(s != word) return false;
}
return true;
}
private: unordered_map<string, vector<string>> mp;
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa(dictionary);
// vwa.isUnique("hello");
// vwa.isUnique("anotherWord");
};


class ValidWordAbbr {
public:
ValidWordAbbr(vector<string> &dictionary) {
for(string s : dictionary){
mp[abbrivate(s)].push_back(s);
}
}
string abbrivate(string s){
int len = s.size();
return len<=2 ? s : s[0] + to_string(len-2) + s[len-1];
}
bool isUnique(string word) {
return (mp[abbrivate(word)].size() == 1 && mp[abbrivate(word)].find(word) != mp[abbrivate(word)].end()) || mp[abbrivate(word)].empty();
}
private: unordered_map<string, unordered_set<string>> mp;
// Your ValidWordAbbr object will be instantiated and called as such:
// ValidWordAbbr vwa(dictionary);
// vwa.isUnique("hello");
// vwa.isUnique("anotherWord");
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode