527. Word Abbreviation

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.
 1 public class Solution {
 2     public List<String> wordsAbbreviation(List<String> dict) {
 3         int len = dict.size();
 4         String[] ans = new String[len];
 5         int[] prefix = new int[len];
 6         for(int i=0;i<len;i++){
 7             prefix[i] = 1;
 8             ans[i] = makeAbbr(dict.get(i),prefix[i]);
 9         }
10         for(int i=0;i<len;i++){
11             while(true){
12                 HashSet<Integer> set = new HashSet<Integer>();
13                 for(int j=i+1;j<len;j++){
14                     if(ans[i].equals(ans[j])){
15                         set.add(j);
16                     }
17                 }
18                 if(set.isEmpty()) break;
19                 set.add(i);
20                 for(Integer s:set){
21                     ans[s] = makeAbbr(dict.get(s),++prefix[s]);
22                 }
23             }
24         }
25         return Arrays.asList(ans);
26     }
27     public String makeAbbr(String s,int k){
28         if(k>=s.length()-2){
29             return s;
30         }
31         StringBuilder sb = new StringBuilder();
32         sb.append(s.substring(0,k));
33         sb.append(s.length()-k-1);
34         sb.append(s.charAt(s.length()-1));
35         return sb.toString();
36     }
37 }
38 //suppose the average of every string could be k,the size of the list could be n,the total run time could be O(n^2*k);the space complexity could be O(n);

 

转载于:https://www.cnblogs.com/codeskiller/p/6906732.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值