Java Practice [HashMap]

Group Anagrams https://leetcode.com/problems/group-anagrams/


 class Solution {

    public List<List<String>> groupAnagrams(String[] strs) {

        

        HashMap<String, List<String>> hm = new HashMap<>();

        

        for(int i=0;i<strs.length;i++) {

            char[] s = strs[i].toCharArray();

            Arrays.sort(s);

            String k = new String(s);

            if(hm.containsKey(k)) {

                hm.get(k).add(strs[i]);

            } else {

                List<String> ls = new ArrayList<String>();

                ls.add(strs[i]);

                hm.put(k,ls);

            }

        }

        

        List<List<String>> ans = new ArrayList<List<String>>();;

        

        for (String p:hm.keySet()) {

          ans.add(hm.get(p));   

        }

        

        return ans;

    }

}

Comments

Popular posts from this blog

Getting Started With MEAN App Development with AngularJs , ExpressJs , NodeJs and MongoDB.

B. Dreamoon and WiFi :calculate no. of ways : recursive solution (branch and bound )

A. Dreamoon and Stairs : minimum steps to reach : recursion solution.