repl.it
@shachopin/

Word Abbreviation

Java

No description

fork
loading
Files
  • Main.java
  • jdt.ls-java-project
Main.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}

MySolution in lintcode 639 Word Abbreviation

public class Solution {
    /**
     * @param dict: an array of n distinct non-empty strings
     * @return: an array of minimal possible abbreviations for every word
     */
    public String[] wordsAbbreviation(String[] dict) {
      
        if (dict == null) {
            return null;
        }
        String[] ans = new String[dict.length];
        Map<String, Integer> countMap = new HashMap<>();
        int round = 1;
        for (int i = 0; i < dict.length; i++) {
            ans[i] = getAbbr(dict[i], round);
            countMap.put(ans[i], countMap.getOrDefault(ans[i], 0) + 1);
        }        
        
        while (true) {
            round++;
            boolean allUnique = true;
            for (int i = 0; i < dict.length; i++) {
                if (countMap.get(ans[i]) > 1) {
                    allUnique = false;
                    ans[i] = getAbbr(dict[i], round);
                    countMap.put(ans[i], countMap.getOrDefault(ans[i], 0) + 1);
                }
            }
            
            if (allUnique) {
                break;
            }
        }
        
        return ans;
        
    }
    
    private String getAbbr(String s, int p) { 
        if (p + 2 >= s.length()) {
            return s;
        }
        String ans;
        ans = s.substring(0, p) + (s.length() - 1 - p) + s.charAt(s.length() - 1);
        return ans;
    }
}