Java simple AC solution with explanation 41ms

  • 3

    The problem is easy but the goal is somewhat confusing and people might misunderstand first time.
    return true : two cases
    case1: the abbreviaction does not exisit in the dictionary.
    case2: it exists and the original word in dictionary is unique and the same as input word.

    public class ValidWordAbbr {
        Map<String, String> dict;
        public ValidWordAbbr(String[] dictionary) {
            dict = new HashMap<>();
            String abbr;
            for (String word : dictionary) {
                abbr = getAbbr(word);
                if (!dict.containsKey(abbr)) //first time to encounter the new abbr
                    dict.put(abbr, word);
                else if (!dict.get(abbr).equals(word)) // next time, original word is different
                    dict.put(abbr, "-1"); // -1: not unique
        public boolean isUnique(String word) {
            String abbr = getAbbr(word);
            if (!dict.containsKey(abbr))
                return true;
                return dict.get(abbr).equals(word) ? true : false;
        private String getAbbr(String word) {
            int n = word.length();
            if (n < 3)
                return word;
            return "" + word.charAt(0) + (n - 2) + word.charAt(n - 1);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.