zoukankan      html  css  js  c++  java
  • 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);
  • 相关阅读:
    任务安排(代价提前付)
    10 01模拟赛订正
    哈希hash
    初学期望
    P1251 递推专练3
    P1229-神秘岛
    P1228-重叠的图像
    白银莲花池
    求强连通分量
    割边
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6906732.html
Copyright © 2011-2022 走看看