The key point of this problem is to find "key" of every words. Time complexity: O(n)
How to find key of every string, we make every key as a string with 'a' as the first character.
1. get "shift": shift = cs[0]-'a';
2. minus every character by "shift"
3. convert the char[] to string
The string of step3 is the "key".
Map<String, List<String>> map = new HashMap<>(); public List<List<String>> groupStrings(String[] strings) { for(String s: strings){ char[] cs = s.toCharArray(); int shift = cs[0]-'a'; for(int i=0;i<cs.length;i++){ cs[i]=(char)(cs[i]-shift); if(cs[i]<'a') cs[i]+=26; } String key = new String(cs); if(!map.containsKey(key)){ map.put(key, new ArrayList<>()); } map.get(key).add(s); } List<List<String>> res = new ArrayList<>(); for(String key: map.keySet()){ res.add(map.get(key)); } return res; }