repl.it
@shachopin/

Unique 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
class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}

MySolution in lintcode 648 Unique Word Abbreviation, 
public class ValidWordAbbr {
    Map<String, Integer> wordToCount = new HashMap<>();
    Map<String, Integer> abbrToCount = new HashMap<>();
    
    public ValidWordAbbr(String[] dictionary) {
        // do intialization if necessary
        for (String word : dictionary) { //count map 的妙用
            wordToCount.put(word, wordToCount.getOrDefault(word, 0) + 1);
            String abbr = getAbbr(word);
            abbrToCount.put(abbr, abbrToCount.getOrDefault(abbr, 0) + 1);
        }
    }

    /*
     * @param word: a string
     * @return: true if its abbreviation is unique or false
     */
    public boolean isUnique(String word) {
        // write your code here
        String abbr = getAbbr(word);
        return wordToCount.getOrDefault(word, 0) == abbrToCount.getOrDefault(abbr, 0);  
    }
    
    private String getAbbr(String word) {
        if (word.length() <= 2) {
            return word;
        }
        
        return "" + word.charAt(0) + (word.length() - 2) + word.charAt(word.length() - 1);
        //光有return word.charAt(0) + (word.length() - 2) + word.charAt(word.length() - 1)不行,因为three parts都不是string
    }
}