Beats 99% 4ms JAVA solution


  • 2
    S
    public class Solution {
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> ans = new ArrayList<>();
    
        //corner cases
        if (strings.length == 0) {
            return ans;
        }
        
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strings) {
            String key = getKey(str);
            if (map.containsKey(key)) {
                map.get(key).add(str);
            } else {
                List<String> list = new ArrayList<>();
                list.add(str);
                map.put(key, list);
            }
        }
        for (List<String> list : map.values()) {
            Collections.sort(list);
            ans.add(list);
        }
        return ans;
    }
    private String getKey(String str) {
        if (str.length() == 0) {
            return "";
        }
        if (str.length() == 1) {
            return "z";
        }
        char[] chars = str.toCharArray();
        int offset = 'z' - chars[0];
        for(int i = 0; i < chars.length; i++) {
            chars[i] += offset;
            if (chars[i] > 'z') {
                chars[i] -= 26;
            }
        }
        return new String(chars);
    }
    

    }


  • 0
    T

    so brilliant, align or normalization (the word maybe inaccurate) the same shifting sequence


  • 0
    T

    this looks awesome! can someone please explain the logic behind getKey() ?

    Thanks


Log in to reply
 

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