Amazon | Onsite | Group Isomorphic Strings

5221
Aug 27, 2019
Aug 27, 2019

Position: SDE II

Given an array of strings, you need to group isomorphic strings together.

Example:

Input: ["apple", "apply", "dog", "cog", "romi"]
Output: [["dog", "cog"], ["romi"], ["apple", "apply"]]
My solution

You have to make the pattern for all the string like for apple >>> 1211 . where a>1 p>2 >l2 and 3>1 and sotre the pattern as a key in map and match if this kind of pattern exist in map then club together all this in one list.

public class GroupOFIsomorpic {

    public static void main(String[] args) {
        String[] list ={"apple","apply","dog","cog","romi"};
        List<List<String>> res = groupIsomorphic(list);
    }

    public static List<List<String>> groupIsomorphic(String[] strs) {
        if(strs.length == 0)
            return null;

        Map<String, List>map = new HashMap <>();
        for(String s : strs){
    
           
            int countindex = 1;
            StringBuilder sb1 = new StringBuilder();
            for(int i=0;i<s.length()-1;i++) {
                if(s.charAt(i) == s.charAt(i+1)) {
                    countindex++;
                   
                    sb1.append(countindex);

                } else {
                    countindex = 1;
                    sb1.append(countindex);
                }
            }

            String key = sb1.toString();
            if(!map.containsKey(key))
                map.put(key,new ArrayList());
              map.get(key).add(s);
        }

        return new ArrayList (map.values());
    }
}
Comments (10)