Straightforward recursive Java Solution, using HashMaps


  • 0
    X
    public class Solution {
        public List<String> wordsAbbreviation(List<String> dict) {
            Map<String,String> map = new HashMap<>();
            helper(map, dict, 1);
            List<String> res = new ArrayList<>();
            for(String word : dict){
                res.add(map.get(word));
            }
            return res;
        }
        
        public void helper(Map<String, String> map, List<String> words, int start){
            Map<String, List<String>> cur = new HashMap<>();
            for(String word : words){
                String abbr = getAbbr(word, start);
                if(!cur.containsKey(abbr)) cur.put(abbr, new ArrayList<>());
                cur.get(abbr).add(word);
            }
            
            for(Map.Entry<String, List<String>> entry : cur.entrySet()){
                if(entry.getValue().size() == 1) map.put(entry.getValue().get(0), entry.getKey());
                else helper(map, entry.getValue(), start + 1);
            }
        }
        
        public String getAbbr(String s, int start){
            if(s.length() <= 3 || start >= s.length() - 2) return s;
            return s.substring(0, start) + (s.length() - start - 1) + s.charAt(s.length() - 1);
        }
    }
    

Log in to reply
 

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