原题链接在这里:https://leetcode.com/problems/word-abbreviation/description/
题目:
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.
题解:
暴力解法把字典里所有的string都最短缩写,遇到重复的就都加个prefix再检查.
Time Complexity: O(mn). m = dict.size(). n是字典里string的平均长度.
Space: O(m).
AC Java:
1 class Solution { 2 public List<String> wordsAbbreviation(List<String> dict) { 3 int len = dict.size(); 4 String [] res = new String[len]; 5 int [] prefix = new int[len]; 6 7 for(int i = 0; i<len; i++){ 8 String abbr = getAbbr(dict.get(i), 0); 9 res[i] = abbr; 10 } 11 12 for(int i = 0; i<len; i++){ 13 while(true){ 14 HashSet<Integer> hs = new HashSet<Integer>(); 15 for(int j = i+1; j<len; j++){ 16 if(res[j].equals(res[i])){ 17 hs.add(j); 18 } 19 } 20 21 if(hs.isEmpty()){ 22 break; 23 } 24 25 hs.add(i); 26 for(int duplicateInd : hs){ 27 res[duplicateInd] = getAbbr(dict.get(duplicateInd), ++prefix[duplicateInd]); 28 } 29 } 30 } 31 32 return Arrays.asList(res); 33 } 34 35 private String getAbbr(String s, int ind){ 36 int len = s.length(); 37 if(len-ind <= 3){ 38 return s; 39 } 40 41 return s.substring(0, ind+1) + (len-ind-2) + s.charAt(len-1); 42 } 43 }