class Solution {
public List<List<String>> groupStrings(String[] strings) {
List<List<String>> res = new ArrayList<>();
if (strings == null || strings.length == 0) return res;
HashMap<String, ArrayList<Integer>> map = new HashMap<>();
for (int i = 0; i < strings.length; i++) {
String str = shift(strings[i]);
if (!map.containsKey(str)) map.put(str, new ArrayList<Integer>());
map.get(str).add(i);
}
for (String str : map.keySet()) {
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < map.get(str).size(); i++) {
list.add(strings[map.get(str).get(i)]);
}
res.add(list);
}
return res;
}
private String shift(String str) {
StringBuilder sb = new StringBuilder();
int gap = str.charAt(0) - 'a';
for (int i = 0; i < str.length(); i++) {
int c = (int)str.charAt(i) - gap;
if ((char)c < 'a') c += 26;
sb.append((char)c);
}
return sb.toString();
}
}
Storing ArrayList as value in the map will make things easier! Also that even saves us some space.
String bytesin Java: Internally - it contains (number of chars) * 2 bytes, as each char in Java takes up two bytes (a normal character in Java is 16 bits unicode). The actual bytes are 0x20 and 0x14.
While int is 4 bytes.
Storing ArrayList as value in the map will make things easier! Also that even saves us some space.
String bytesin Java: Internally - it contains (number of chars) * 2 bytes, as each char in Java takes up two bytes (a normal character in Java is 16 bits unicode). The actual bytes are 0x20 and 0x14.
While int is 4 bytes.