1. 程式人生 > >Leetcode 527. Word Abbreviation

Leetcode 527. Word Abbreviation

doesn win make bbr 形式 ack ike origin until

Problem:

Given an array of n distinct non-empty strings, you need to generate minimal possible abbreviations for every word following rules below.

  1. Begin with the first character and then the number of characters abbreviated, which followed by the last character.
  2. 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.
  3. 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:
  1. Both n and the length of each word will not exceed 400.
  2. The length of each word is greater than 1.
  3. The words consist of lowercase English letters only.
  4. 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 };

Leetcode 527. Word Abbreviation