My Java Solution : Beats 95% Java Solutions


  • 0
    G
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            HashMap<String,List<String>> hm = new HashMap<>();
            String sorted;
            List<List<String>> result = new ArrayList<>();
            for (String s:strs){
                sorted = getSortedString(s);
                if(hm.containsKey(sorted)){
                    List<String> ls = hm.get(sorted);
                    ls.add(s);
                } else {
                    List<String> ls = new ArrayList<String>();
                    ls.add(s);
                    hm.put(sorted,ls);
                    result.add(ls);
                }
            }
            return result;
        }
        
        public String getSortedString(String s){
            char[] chars = s.toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        }
    }
    

Log in to reply
 

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