leetcode-study

290. Word Pattern

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        """
        Check if a string 's' follows the same bijective word pattern as given in 'pattern'.
        
        Parameters:
            pattern (str): A string representing the pattern where each character corresponds to a unique word.
            s (str): A string containing words separated by a single space.
        
        Returns:
            bool: True if 's' follows the same bijective pattern as 'pattern', False otherwise.
        """
        words = s.split()  # Split the string into a list of words.
        
        # If the number of letters in the pattern does not match the number of words, return False.
        if len(pattern) != len(words):
            return False
        
        # Dictionaries to establish mapping from pattern to words and vice versa.
        char_to_word = {}
        word_to_char = {}
        
        # Iterate over the pattern and corresponding word.
        for char, word in zip(pattern, words):
            # Check if there is an existing mapping from character to word.
            if char in char_to_word:
                # If the existing mapping does not match the current word, return False.
                if char_to_word[char] != word:
                    return False
            else:
                char_to_word[char] = word  # Establish new mapping from character to word.
                
            # Check if there is an existing mapping from word to character.
            if word in word_to_char:
                # If the existing mapping does not match the current character, return False.
                if word_to_char[word] != char:
                    return False
            else:
                word_to_char[word] = char  # Establish new mapping from word to character.
        
        # If all mappings are consistent, the pattern is followed.
        return True

Summary of Techniques and Approaches: