You are provided with a list of strings called words
and a single string called pattern
. Your task is to find all words in the list that match the pattern. A word matches the pattern if there exists a permutation of letters, such that after relabeling the pattern letters the word matches the exact pattern string.
For instance, if the pattern is “abb” and there is a word “xyz”, “xyz” matches because we can map ‘a’ <-> ‘x’ and ‘b’ <-> ‘y’.
Input: words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output: ["mee","aqq"]
words
and pattern
consist of lowercase English letters.To solve this problem, we can use the following approach:
pattern_match
that constructs a unique representation for a given string based on the order of appearance of characters. For example, the string “abb” would translate to the pattern “0,1,1”.Here’s the code based on the above strategy:
from typing import List
def findAndReplacePattern(words: List[str], pattern: str) -> List[str]:
def pattern_match(word: str) -> List[int]:
m = {}
return [m.setdefault(c, len(m)) for c in word]
pattern_rep = pattern_match(pattern)
return [word for word in words if pattern_match(word) == pattern_rep]
# Example Usage
words = ["abc", "deq", "mee", "aqq", "dkd", "ccc"]
pattern = "abb"
output = findAndReplacePattern(words, pattern)
print(output) # Output: ['mee', 'aqq']
This approach efficiently solves the given problem within the provided constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?