5ms Java Solution


  • 3
    S
    public List<List<String>> groupStrings(String[] strings) {
        List<List<String>> lists = new ArrayList<List<String>> ();
        if(strings == null || strings.length == 0){
            return lists;
        }
        
        Map<String, List<String>> map = new HashMap<String, List<String>> ();
        for(String str : strings){
            String s = convert(str);
            if(!map.containsKey(s)){
                map.put(s, new ArrayList<String> ());
            }
            map.get(s).add(str);
        }
        for(List<String> list : map.values()){
            Collections.sort(list);
            lists.add(list);
        }
        return lists;
    }
    
    private String convert(String s){
        int shift = 'z' - s.charAt(0);
        char[] arr = s.toCharArray();
        for(int i = 0; i < arr.length; i++){
            arr[i] = (arr[i] + shift > 'z') ? ((char)( (arr[i] + shift - 'z') + 'a' - 1)) : (char)(arr[i] + shift);
        }
        return new String(arr);
    }

Log in to reply
 

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