I have solved the GROUP ANAGRAM question in leetcode in two ways.Why one of them is not giving correct result whereas the other one is returing null?

huangapple go评论147阅读模式
英文:

I have solved the GROUP ANAGRAM question in leetcode in two ways.Why one of them is not giving correct result whereas the other one is returing null?

问题

给定一个字符串数组strs,将其中的异位词分组在一起。你可以以任何顺序返回答案。

解法1:正确的解法:

public List<List<String>> groupAnagrams(String[] strs) {
    HashMap<String, List<String>> hm = new HashMap<>();

    for (String st : strs) {
        char[] arr = st.toCharArray();
        Arrays.sort(arr);
        String canonical = new String(arr);
        if (!hm.containsKey(canonical)) {
            hm.put(canonical, new LinkedList<String>());
        }

        hm.get(canonical).add(st);
    }

    return new LinkedList<>(hm.values());
}

解法2:错误的解法:

public List<List<String>> groupAnagrams(String[] strs) {
    HashMap<String, List<String>> hm = new HashMap<>();

    for (String st : strs) {
        char[] arr = st.toCharArray();
        Arrays.sort(arr);
        String canonical = new String(arr);

        hm.getOrDefault(canonical, new LinkedList<String>()).add(st);

    }
    return new LinkedList<>(hm.values());
}

为什么解法2不起作用,当两个代码非常相似时?

英文:

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

Solution 1:the correct one:

public List&lt;List&lt;String&gt;&gt; groupAnagrams(String[] strs) {
        HashMap&lt;String,List&lt;String&gt;&gt; hm=new HashMap&lt;&gt;();   
        
        for(String st:strs){
            char[] arr=st.toCharArray();
            Arrays.sort(arr);
            String cannonical=new String(arr);
            if(!hm.containsKey(cannonical)){
                hm.put(cannonical,new LinkedList&lt;String&gt;());
            }
            
            hm.get(cannonical).add(st);
        }
       
        return new LinkedList&lt;&gt;(hm.values());
    }

Solution 2:Incorrect :

public List&lt;List&lt;String&gt;&gt; groupAnagrams(String[] strs) {
        HashMap&lt;String,List&lt;String&gt;&gt; hm=new HashMap&lt;&gt;();   
        
        for(String st:strs){
            char[] arr=st.toCharArray();
            Arrays.sort(arr);
            String cannonical=new String(arr);
            
             hm.getOrDefault(cannonical,new LinkedList&lt;String&gt;()).add(st);
            
        }
        return new LinkedList&lt;&gt;(hm.values());
    }

why soln 2 is not working when both the codes are very similar

答案1

得分: 1

在解决方案1中,当你使用hm.put(cannonical,new LinkedList&lt;String&gt;())在HashMap中创建一个新条目时,你确保如果HashMap中不存在cannonical键,就会创建一个新的LinkedList并与该键关联。

这样,当你稍后调用hm.get(cannonical).add(st)时,你可以确保与cannonical键关联的是一个List<String>,并且可以安全地将当前字符串st添加到该列表中

在解决方案2中,错误的部分在这里:

hm.getOrDefault(cannonical, new LinkedList&lt;String&gt;()).add(st);

getOrDefault方法将返回与cannonical键关联的现有列表或新创建的列表,但是这个新创建的列表实际上从未放入HashMap中。因此,即使你正确地检索到了列表,你修改的是一个与HashMap中的任何键都不关联的列表

正确的版本应该是:

hm.putIfAbsent(cannonical, new LinkedList&lt;String&gt;());
hm.get(cannonical).add(st);

在这里,putIfAbsent确保与cannonical键关联一个列表,然后你可以安全地将当前字符串添加到该列表中

英文:

In Solution 1, when you create a new entry in the HashMap using hm.put(cannonical,new LinkedList&lt;String&gt;()) , you ensure that if the cannonical key doesn't exist in the HashMap, a new LinkedList is created and associated with that key.

This way, when you later call hm.get(cannonical).add(st), you are sure that there is a List<String> associated with the cannonical key, and you can safely add the current string st to that list.

In Solution 2, the incorrect part is here:

hm.getOrDefault(cannonical, new LinkedList&lt;String&gt;()).add(st);

The getOrDefault method will return either the existing list associated with the cannonical key or the newly created list, but this newly created list is never actually put into the HashMap. So, even though you correctly retrieve the list, you're modifying a list that's not associated with any key in the HashMap.

The correct version would be:

hm.putIfAbsent(cannonical, new LinkedList&lt;String&gt;());
hm.get(cannonical).add(st);

Here, putIfAbsent ensures that a list is associated with the cannonical key, and then you can safely add the current string to that list.

答案2

得分: 0

这是问题所在。

hm.getOrDefault(cannonical, new LinkedList<String>()).add(st);

没有找到键,所以你正在尝试将一个值添加到一个没有映射的列表中。

将其替换为:

hm.computeIfAbsent(cannonical, v -> new LinkedList<>()).add(st);

上述代码的意思是,如果 cannonical 不存在,则创建一个值,并返回该值,这里是一个列表。然后你可以将字符串添加到列表中。

英文:

This is the problem.

 hm.getOrDefault(cannonical,new LinkedList&lt;String&gt;()).add(st);

There is no key so you are trying to add a value to a list that isn't mapped.

Replace it with

hm.computeIfAbsent(cannonical, v-&gt; new LinkedList&lt;&gt;()).add(st);

The above says, if cannonical is not present, create a value for it, and return that value, in this case a list. Then you can add the string to the list.
`

huangapple
  • 本文由 发表于 2023年8月8日 22:45:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76860677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定