
Problem Statement
The task is to determine if a given string s follows the same pattern defined by another string pattern. The string s must match the pattern such that a letter from pattern corresponds exactly and exclusively to a non-empty word in s. This challenge requires establishing a bijection, meaning:
- Each letter in
patternshould map to one unique word ins. - Each word in
sshould correspond to one unique letter inpattern. - The relationship between letters and words should be consistent throughout the string and pattern; no letter can map to more than one word, and no word can map to more than one letter.
This clearly defined relationship should hold for the entirety of both the pattern and s.
Examples
Example 1
Input:
pattern = "abba", s = "dog cat cat dog"
Output:
true
Explanation:
The bijection can be established as: * `'a'` maps to `"dog"`. * `'b'` maps to `"cat"`.
Example 2
Input:
pattern = "abba", s = "dog cat cat fish"
Output:
false
Example 3
Input:
pattern = "aaaa", s = "dog cat cat dog"
Output:
false
Constraints
1 <= pattern.length <= 300patterncontains only lower-case English letters.1 <= s.length <= 3000scontains only lowercase English letters and spaces' '.sdoes not contain any leading or trailing spaces.- All the words in
sare separated by a single space.
Approach and Intuition
To determine if "s" follows the described pattern:
First, split string
sinto individual words based on spaces, as each word will potentially map to a letter inpattern.Check if the number of words in
smatches the length ofpattern. If they do not match, it is impossible forsto follow the pattern.Utilize two hash maps to ensure the bijection, where:
- One maps characters from
patternto words ins. - The other maps words in
sback to characters frompattern.
- One maps characters from
Iterate over each letter in
patternand the corresponding word ins(obtained from splitting):- For each mapping:
- If a letter in
patternis seen for the first time, map it to the current word ins. Simultaneously, map the word insto the letter inpattern. - If a letter or a word is repeatedly seen, check their mappings. If any of the current mappings disagree with previously established mappings, return
falseindicating thatsdoes not followpattern.
- If a letter in
- For each mapping:
If you successfully navigate the entire pattern without conflicts in mapping, return
true.
Considerations Based on Given Examples
- Consider how words match with characters and how variations from these allocations lead to a
falseoutcome. For example,- If two different characters in
patternmap to the same word ins, it breaks the rule of bijection. - Similarly, if a single character is supposed to map to different words at different occurrences, it signifies a violation of the pattern rule.
- If two different characters in
Using hash maps allows for an efficient check of these relationships while iterating through both the pattern and the string only once, ensuring a time complexity that is linear relative to the size of s and pattern.
Solutions
- Java
- Python
class Solution {
public boolean isPatternMatching(String pat, String str) {
HashMap patternMap = new HashMap();
String[] words = str.split(" ");
if (words.length != pat.length())
return false;
for (Integer index = 0; index < words.length; index++) {
char p = pat.charAt(index);
String word = words[index];
if (!patternMap.containsKey(p))
patternMap.put(p, index);
if (!patternMap.containsKey(word))
patternMap.put(word, index);
if (patternMap.get(p) != patternMap.get(word))
return false;
}
return true;
}
}
The given Java code defines a method to determine if a string follows a specific pattern. The method isPatternMatching accepts two strings, pat and str, where pat is a pattern of characters and str is a string of words separated by spaces.
Here’s a breakdown of how the code works:
- A
HashMapcalledpatternMapis initialized to store the relationship between the characters in the pattern and the words in the string. - The string
stris split into an array of words. - If the number of words in
strdoes not match the length ofpat, the method returnsfalseimmediately. - A loop iterates through each character of the pattern:
- For each character
pand the corresponding word fromstr, the code checks if both are already present inpatternMap. - If
por the word is not present in the map, it gets added with its current index as the value. - The method checks if the indices stored for
pand the word inpatternMapmatch. If they differ,falseis returned.
- For each character
- If all pattern and word pairs have the same mapping throughout the loop, the method returns
true.
This approach uses the properties of a HashMap to ensure that each character in the pattern consistently maps to the same word in the string and vice versa, thus determining if str follows the pattern described in pat.
class Solution:
def isPatternMatch(self, pattern: str, string: str) -> bool:
index_map = {}
string_words = string.split()
if len(pattern) != len(string_words):
return False
for index in range(len(string_words)):
pattern_char = pattern[index]
current_word = string_words[index]
key_char = 'char_{}'.format(pattern_char)
key_word = 'word_{}'.format(current_word)
if key_char not in index_map:
index_map[key_char] = index
if key_word not in index_map:
index_map[key_word] = index
if index_map[key_char] != index_map[key_word]:
return False
return True
The "Word Pattern" problem is to determine if a given string follows a specific pattern. This solution is implemented in Python. Here's a summary of how the code tackles the problem:
- Initializes an empty dictionary
index_mapto track mappings between pattern characters and words in the string. - Splits the input string into words using
split()method and stores them instring_words. - Verifies if the number of characters in the pattern is the same as the number of words in the string. If they differ, the function returns
Falseimmediately as the pattern cannot be matched. - Iterates through the characters in the pattern and the corresponding words in
string_words.- For each character and word, creates a unique key by combining the character or word with a prefix (
char_for characters andword_for words). - Checks if the keys exist in
index_map. If a key does not exist, it maps the key to its current index. - Compares the indices mapped to each pattern character and the corresponding word. If they differ at any point, it indicates a mismatch in the pattern mapping, thus the function returns
False.
- For each character and word, creates a unique key by combining the character or word with a prefix (
- If the loop completes without finding mismatches, it returns
True, indicating the pattern matches the string words.
This method effectively checks pattern consistency using indexed mapping, ensuring that both pattern characters and words in the string correlate directly to the same indices throughout the sequence.