LeeCode49 letter dysphoric grouping (Java) (hash or string sort)

Topic link: LeeCode49 letter dysphoric grouping
Topic description: The Insert picture description here
first idea to get the question is to sort the strings and compare the same strings stored in hashmap after all strings are sorted, and then write the first solution

public static List<List<String>> groupAnagrams(String[] strs) {
    
    
        List<List<String>> lists=new ArrayList<>();
        Map<String,List<String>> map=new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
    
    
            char[] chars=strs[i].toCharArray();
            Arrays.sort(chars);
            String s = String.valueOf(chars);
            if(!map.containsKey(s)){
    
    
                List<String> list=new ArrayList<>();
                list.add(strs[i]);
                map.put(s,list);
            }else{
    
    
                List<String> list = map.get(s);
                list.add(strs[i]);
                map.put(s,list);
            }
        }
        for (List<String> value : map.values()) {
    
    
            lists.add(value);
        }
        return lists;
    }

Then I feel that I’m not too fast to solve the problem and learn the idea of ​​hashing. I rewrite a hash function by myself. You can treat abc and bac as the same type of string and then calculate them to return the same hash value. The difficulty lies in the formula It must be hashed as much as possible, otherwise the ghost knows what bizarre and similar examples will come out

class Solution {
    
    
    public static List<List<String>> groupAnagrams(String[] strs) {
    
    
        List<List<String>> lists=new ArrayList<>();
        Map<Long ,List<String>> map=new HashMap<>();
        for (int i = 0; i < strs.length; i++) {
    
    
            Long hash = hash(strs[i]);
            if(map.containsKey(hash)){
    
    
                List<String> list = map.get(hash);
                list.add(strs[i]);
                map.put(hash,list);
            }else{
    
    
                List<String> list=new ArrayList<>();
                list.add(strs[i]);
                map.put(hash,list);
            }
        }
        for (List<String> value : map.values()) {
    
    
            lists.add(value);
        }
        return lists;
    }
    public static Long hash(String s){
    
    
        char[] chars = s.toCharArray();
        long ans=0;
        for (int i = 0; i < chars.length; i++) {
    
    
            char c='a'-2;
            long i1=chars[i]-c;;
            ans+=(3*i1*i1*i1)*i1*+(5*i1*i1*i1)/33+(i1*i1)*333%10+i1*33;
        }
        return ans;
    }
}

Guess you like

Origin blog.csdn.net/weixin_43590593/article/details/112603833
Recommended