
Problem Statement
Given a list of word strings and a single pattern string, the task is to identify which words from the list match the provided pattern. Two strings are considered a match if one can morph into the other by a consistent replacement of characters, such that every letter in the pattern maps uniquely to another letter, forming a bijective relationship.
A crucial condition for two strings to match under the given rules is that these replacements form a perfect one-to-one mapping, where each letter in the pattern maps to a unique letter in the word. This means that no two different letters in the pattern should map to the same letter in the potential matching word.
Examples
Example 1
Input:
words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
Output:
["mee","aqq"]
Explanation:
"mee" matches the pattern because there is a permutation {a -> m, b -> e, ...}. "ccc" does not match the pattern because {a -> c, b -> c, ...} is not a permutation, since a and b map to the same letter.
Example 2
Input:
words = ["a","b","c"], pattern = "a"
Output:
["a","b","c"]
Constraints
1 <= pattern.length <= 20
1 <= words.length <= 50
words[i].length == pattern.length
pattern
andwords[i]
are lowercase English letters.
Approach and Intuition
In order to solve this, you need to compare the structure of each word against the pattern. The main idea is to establish a mapping based on the position of characters:
- If the first occurrence of a character in the pattern is at the same position as the first occurrence of a corresponding character in the word, and this persists for every character and their corresponding pair, then the word matches the pattern.
Based on the above point:
- For every word in the list, create this character-to-character mapping with the pattern.
- Check for consistency in this mapping throughout the word. If at any point, the mapping diverges (i.e., a single pattern character tries to map to more than one character or vice-versa), discard this word as it doesn't fit the pattern.
Store the words that successfully match this mapping criterion and return them as the output. This matching ensures that the permutation of letters is a bijective (one-to-one and onto) function, meeting the problem's requirement that no two letters map to the same target letter.
Examples:
- For the word "mee" and the pattern "abb", we see that first occurrences of 'a' in "abb" and 'm' in "mee" coincide. Similarly, 'b' maps consistently to 'e', hence "mee" matches "abb".
- The word "ccc" against the pattern "abb", however, fails to meet criteria, as different pattern characters ('a' and 'b') map to the same character ('c'), invalidating the bijective requirement.
From these application points, it's clear that the mapping of characters from the pattern to the word (and vice versa) while maintaining the consistency and uniqueness of these mappings forms the core logic of this problem.
Solutions
- Java
class Solution {
public List<String> filterByPattern(String[] phraseArray, String model) {
List<String> matches = new ArrayList<>();
for (String phrase: phraseArray)
if (isMatch(phrase, model))
matches.add(phrase);
return matches;
}
public boolean isMatch(String phrase, String model) {
Map<Character, Character> characterMap = new HashMap<>();
for (int i = 0; i < phrase.length(); ++i) {
char charFromPhrase = phrase.charAt(i);
char charFromModel = model.charAt(i);
if (!characterMap.containsKey(charFromPhrase)) characterMap.put(charFromPhrase, charFromModel);
if (characterMap.get(charFromPhrase) != charFromModel) return false;
}
boolean[] marked = new boolean[26];
for (char val: characterMap.values()) {
if (marked[val - 'a']) return false;
marked[val - 'a'] = true;
}
return true;
}
}
In this Java solution for the problem of finding and replacing patterns in strings, you work with a method called filterByPattern
which filters out strings that match a given pattern (model
) from an array of strings (phraseArray
). Here's a breakdown of how the solution achieves this task:
Method
filterByPattern
:- Initializes an empty list
matches
to store strings that match the pattern. - Iterates over each string in
phraseArray
. For each string, it calls theisMatch
method to check if the current string matches the pattern. - If a string matches (i.e.,
isMatch
returnstrue
), it is added tomatches
. - Finally, it returns the list of matches.
- Initializes an empty list
Method
isMatch
:- Initializes a
characterMap
to map characters from the input string (phrase
) to characters in the pattern (model
). - Iterates over characters in the string
phrase
, simultaneously comparing them with corresponding characters inmodel
. - Maps characters from
phrase
tomodel
usingcharacterMap
if they're not already mapped. - Verifies that no two different characters from
phrase
map to the same character inmodel
by using amarked
array. - Ensures that all mappings are unique and consistent throughout the string.
- Returns
true
if all conditions are met for a match, otherwise returnsfalse
.
- Initializes a
Important Points:
- Ensures each character in
phrase
maps to a unique character inmodel
using a hash map, and no character inmodel
is associated with multiple characters fromphrase
using an array to mark used characters. - It preserves the order of characters and enforces a one-to-one mapping, ensuring patterns are matched exactly as intended.
This implementation effectively uses data structures like maps and arrays to enforce pattern consistency and uniqueness, enabling efficient pattern matching against a list of strings.
No comments yet.