https://leetcode.com/problems/find-and-replace-pattern/

Based on this intuition, try solving on our own before looking at the code.

We are given ["abc","deq","mee","aqq","dkd","ccc"] these words and a pattern = "abb" .
Our desired output should be: ["mee","aqq"]

so,

a -> m
b -> e
b -> e

or

a -> a
b -> q
b -> q

Can you see the pattern?

What if we flatten all the character.

1 -> 1
2 -> 2
2 -> 2

This is the idea behind this intuition.

So, we can create a subroutine getFlattenedPattern, which will give us a flattened string of the input string.

In the getFlattenedPattern we start mapping first character to 1 and so on. Also we need to keep to track of preveiously mapped character with a hashtable.

So, our algo for this one, will look something like this:

Map first character to 1 (Put it in a hashtable).
Check hashtable whether subsequent character exist or not in the hashtable.
If it is, append the previously mapped value to the resulting stringbuilder. Otherwise increment our map counter and append.

Once that is done getFlattenedPattern should return "122" for "abb" or "mee". Based on the new pattern you can easily tell whether they should or shouldn't be on our list.

Solution[Java]:

    private String getFlattenedPattern(String word){
        Map<Character, Integer> map = new HashMap<>();
        StringBuilder sb = new StringBuilder();        
        int i = 1;
        int j = 1;
        sb.append(i);
        map.put(word.charAt(0),1);
        while(j<word.length()){
            if(map.containsKey(word.charAt(j))){
                sb.append(map.get(word.charAt(j)));
            }else{                
                i++;
                map.put(word.charAt(j),i);
                sb.append(i);
            }
            j++;            
        }
        return sb.toString();
    }
    
    public List<String> findAndReplacePattern(String[] words, String pattern) {
        List<String> res  = new LinkedList<>();
        if(words==null || words.length==0 || pattern==null || pattern.length()==0){
            return res;
        }
        String ptr = getFlattenedPattern(pattern);
        for(String word: words){
            String str = getFlattenedPattern(word);
            if(str.equals(ptr)){
                res.add(word);
            }
        }
        return res;
    }