Java solution with hashmap


  • 0
    R

    '''import static java.util.Arrays.*;
    public class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
    // Hashmap of sorted char's of the string as key and actual string as value
    HashMap<String,List<String>> listofStringWithAsciSum=new HashMap<>();
    // Final Result variable
    ArrayList<List<String>> result=new ArrayList<>();

    // Iterate for each string in the input array convert to char array and sort the elements in the char array and put to hash map with key as sorted key's string and value as actual string. so anagrams will have same sorted char's will be on same key
    for (String str : strs) {
    char[] strToCharArray=str.toCharArray();
    sort(strToCharArray);
    String str1=new String();

            for(char iter:strToCharArray){
                str1 +=iter;
    
            }
    
    
    
            if(listofStringWithAsciSum.containsKey(str1)){
                List<String> temp=listofStringWithAsciSum.get(str1);
                temp.add(str);
                listofStringWithAsciSum.put(str1,temp);
            }
            else{
                List<String> temp = new ArrayList<String>();
                temp.add(str);
                listofStringWithAsciSum.put(str1,temp);
            }
    
         }
    
            Set<String> keylist=listofStringWithAsciSum.keySet();
        for (String iter : keylist) {
            result.add(listofStringWithAsciSum.get(iter));
    
    
        }
    
        return result;
    }
    

    }'''


Log in to reply
 

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