Java based solution using HashMap


  • 0
    C

    The idea is to generate a Key for each String given by calculating the floorMod between the two adjacent characters. Two strings that map to same key will be stored in same list.

    This approach can be extended to Group Anagrams problem also. Any comments greatly appreciated.

    public List<List<String>> groupStrings(String[] strings) {
            List<List<String>> results = new ArrayList<>();
            HashMap<String, List<String>> map = new HashMap<>();
            for(int i = 0; i < strings.length; i++) {
                String key = "";
                for(int j = 0; j < strings[i].length() - 1; j++) {
                    key += "{"+Math.floorMod(((int)strings[i].charAt(j) - 'a') - ((int) strings[i].charAt(j+1) - 'a'), 26)+"}";
                }
    
                // System.out.println(key);
                List<String> lst;
                if(!map.containsKey(key)) {
                    lst = new ArrayList<>();
                } else {
                    lst = (List<String>) map.get(key);
                }
                lst.add(strings[i]);
                map.put(key, lst);
            }
            for(Map.Entry<String, List<String>> entry: map.entrySet()) {
                results.add(entry.getValue());
            }
            return results;
        }
    

Log in to reply
 

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