Leetcode 527. Word Abbreviation
Problem:
Given an array of n distinct non-empty strings, you need to generate minimal possible abbreviations for every word following rules below.
- Begin with the first character and then the number of characters abbreviated, which followed by the last character.
- If there are any conflict, that is more than one words share the same abbreviation, a longer prefix is used instead of only the first character until making the map from word to abbreviation become unique. In other words, a final abbreviation cannot map to more than one original words.
- If the abbreviation doesn't make the word shorter, then keep it as original.
Example:
Input: ["like", "god", "internal", "me", "internet", "interval", "intension", "face", "intrusion"] Output: ["l2e","god","internal","me","i6t","interval","inte4n","f2e","intr4n"]Note:
- Both n and the length of each word will not exceed 400.
- The length of each word is greater than 1.
- The words consist of lowercase English letters only.
- The return answers should be in the same order as the original array.
Solution:
这道题是要我们为输入字符串中的每个单词找到最短的缩写且不存在冲突,这里要注意下,比如intension和intrusion两个单词,i7n,in6n,int5n都存在两个单词与之对应,因此这题的缩写的含义是要找一个最短的缩写,使得不存在多个单词与之对应,所以这三种缩写形式都无法使用。这道题我们定义一个abbreviate函数,k代表缩写字符串中数字之前的字符个数,比如in6n对应的k等于2。pre数组用于存储前缀的长度信息,初始化为1。首先对于所有字符串先进行一个缩写,然后找出所有出现多次的字符串,增加其前缀的长度重新进行缩写,指到所有缩写都不存在冲突为止。
Code:
1 class Solution { 2 public: 3 string abbreviate(string &str,int k){ 4 if(str.size()-2 <= k) 5 return str; 6 return str.substr(0,k)+to_string(str.size()-1-k)+str.back(); 7 } 8 vector<string> wordsAbbreviation(vector<string>& dict) { 9 int m = dict.size(); 10 vector<string> result(m); 11 vector<int> pre(m,1); 12 for(int i = 0;i != m;++i){ 13 result[i] = abbreviate(dict[i],pre[i]); 14 } 15 for(int i = 0;i != m;++i){ 16 while(true){ 17 unordered_set<int> us; 18 for(int j = i+1;j != m;++j){ 19 if(result[i] == result[j]) 20 us.insert(j); 21 } 22 if(us.empty()) break; 23 us.insert(i); 24 for(auto index:us) 25 result[index] = abbreviate(dict[index],++pre[index]); 26 } 27 } 28 return result; 29 } 30 };