Sunday, 2 May 2021

Group Shifted Strings

 


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;

    }

}



output:

{25#=[az, ba], 1#1#=[abc, bcd, xyz, pqr], 2#2#1#=[acef], #=[a, z], 2#2#=[ace, jln]}

[[az, ba], [abc, bcd, pqr, xyz], [acef], [a, z], [ace, jln]]

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐢𝐧 𝐋𝐢𝐧𝐤𝐞𝐝 𝐋𝐢𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀𝐥𝐥 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 𝐓𝐫𝐞𝐞 𝐓𝐫𝐚𝐯𝐞𝐫𝐬𝐚𝐥𝐬...