share my java solution, easy to understand,come on give me some votes!


  • 0
    T
    public class Solution {
        public List<String> wordsAbbreviation(List<String> dict) {
           if(dict==null || dict.size()<1){
                return new ArrayList<String>();
            }
            List<String> res=Arrays.asList(new String[dict.size()]);
            
            Map<String,List<Integer>> map=new HashMap<>();
            Map<String,Integer> hm=new HashMap<>();
            
            for(int i=0;i<dict.size();i++){
                String abbreviation=abbre(dict.get(i),1);
                if(!map.containsKey(abbreviation)){
                    map.put(abbreviation,new ArrayList<>());
                }
                map.get(abbreviation).add(i);
            }
            
            int level=0;
            while(map.size()!=0){
                level++;
                
                List<String> listArray=new ArrayList<>(map.keySet());
                for(String key:listArray){
                    if(map.get(key).size()==1){
                        hm.put(key,map.get(key).get(0));
                        map.remove(key);
                        continue;
                    }
                    
                    List<Integer> tempList=map.get(key);
                    
                    for(Integer index:tempList){
                        String t_str=abbre(dict.get(index),level+1);
                        
                        if(!map.containsKey(t_str)){
                            map.put(t_str,new ArrayList<>());
                        }
                        
                        map.get(t_str).add(index);
                    }
                    
                    map.remove(key);
                }
            }
            
            for(String key:hm.keySet()){
                res.set(hm.get(key),key);
            }
            return res;
            
        }  
        
        public String abbre(String str,int k){
            if(str.length()<=3) return str;
            
            StringBuilder strbuild=new StringBuilder();
            strbuild.append(str.substring(0,k));
            strbuild.append(str.length()-k-1);
            strbuild.append(str.charAt(str.length()-1));
            
            String ans=strbuild.toString();
            if(ans.length()>=str.length()){
                return str;
            }
            return ans;
        }
    }
    
    

Log in to reply
 

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