290. Word Pattern

# Easy

Two methods:

  1. Because this problem requireds one to one map, we need two maps, {word: letter} and {letter:word}

  2. One hash map, each word and letter maps to its index of its first appearing in the lists

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split(" ")
        # edge case
        if len(words) != len(pattern):
            return False
        
        # regular case
        m1 = {}
        m2 = {}
        for x, y in zip(pattern, words):
            if x in m1 and y in m2:
                if m1[x] != y or m2[y] != x:
                    return False
            else:
                if x not in m1 and y not in m2:
                    m1[x] = y
                    m2[y] = x
                else:
                    return False
        return True

Last updated