Monday, September 21, 2020

LeetCode [527] Word Abbreviation

 527. Word Abbreviation

Hard

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
    String makeAbbr(String word, int k){
        int sz = word.length();
        if(k>=sz-2) return word;
        String tmp = word.substring(0, k) + (sz-k-1) + word.substring(sz-1, sz);
        return tmp.length()<sz ? tmp : word;
    }

    public List<String> wordsAbbreviation(List<String> dict) {
        int n = dict.size();
        int[] abbrs = new int[n];//savedLetterCount;
        Map<String, Set<Integer>> map = new HashMap<>();//abbr, dict[index] has abbr
        boolean valid = true;
        for(int i=0; i<n; ++i){ 
            abbrs[i] = 1;
            String ab = makeAbbr(dict.get(i), 1);
            if(map.containsKey(ab)) valid = false;
            map.computeIfAbsent(ab, k->new HashSet<Integer>()).add(i);
        }


        while(!valid){
            valid = true;
            Map<String, Set<Integer>> mapNew = new HashMap<>();
            for(Map.Entry<String, Set<Integer>> entry : map.entrySet()){
                Set<Integer> invalidAbbrs = entry.getValue();
                if(invalidAbbrs.size()==1) continue;
                for(int i : invalidAbbrs){
                    String ab = makeAbbr(dict.get(i), ++abbrs[i]);
                    if(mapNew.containsKey(ab)) valid = false;
                    mapNew.computeIfAbsent(ab, k->new HashSet<Integer>()).add(i);
                }
            }
            map = mapNew;
        }

        List<String> ret = new ArrayList<>();
        for(int i=0; i<n; ++i) ret.add(makeAbbr(dict.get(i), abbrs[i]));
        return ret;
    }
}

No comments:

Post a Comment