import java.util.*;
//https://www.youtube.com/watch?v=uEXJSRLqoKY&t=54s
public class GroupShiftedStrings {
public static void main(String[] args) {
String arr[] = {"abc","bcd","acef","xyz","az","ba","a","z","pqr","ace","jln"};
List<List<String>> result = groupStrings(arr);
System.out.println(result);
}
private static List<List<String>> groupStrings(String[] arr) {
Map<String, List<String>> map = new HashMap<>();
for(int i = 0;i<arr.length;i++){
char[] charArr = arr[i].toCharArray();
String key = "";
if(charArr.length==1){
key = "#";
}else{
for(int j=1; j<charArr.length;j++){
int diff = (int)(charArr[j]-charArr[j-1]);
if(diff<0){
diff = diff+26;
}
key = key + diff+"#";
}
}
List<String> list = null;
if(map.containsKey(key)){
list = map.get(key);
}else{
list = new ArrayList<>();
}
list.add(arr[i]);
map.put(key,list);
}
System.out.println(map);
List< List<String>> result = new ArrayList<>();
map.forEach((k,v)-> Collections.sort(v));
result.addAll(map.values());
return result;
}
}
No comments:
Post a Comment