JAVA using HashMap


  • 1
    T
    public class Solution {
        public List<List<String>> groupAnagrams(String[] strs) {
            Arrays.sort(strs);
            Map<String, Integer> isGeted = new HashMap<>();
            List<List<String>> result = new ArrayList<List<String>>();
            for (int i=0; i<strs.length; i++){
                String code = getHashCode(strs[i]);
                if (isGeted.containsKey(code) == false){
                    result.add(new ArrayList<String>(Arrays.asList(strs[i])));
                    isGeted.put(code, result.size()-1);
                }else{
                    int index = isGeted.get(code);
                    result.get(index).add(strs[i]);
                }
            }
            return result;
        }
        public String getHashCode(String s){
            char[] arr = s.toCharArray();
            Arrays.sort(arr);
            return new String(arr);
        }
    }

  • 0
    F

    one rule is each inner list's elements must follow the lexicographic order.
    wondering if your code achieve that.

    edit: sorry , i miss Arrays.sort() part. :)


  • 0
    T

    never mind. thanks for your reply:)


Log in to reply
 

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