> For the complete documentation index, see [llms.txt](https://r24zeng.gitbook.io/leetcode-notebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://r24zeng.gitbook.io/leetcode-notebook/bu-chong-81100-dao/290.-word-pattern.md).

# 290. Word Pattern

\# Easy

{% hint style="info" %}
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
   {% endhint %}

{% tabs %}
{% tab title="Python-method1" %}

```python
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
```

{% endtab %}

{% tab title="Python-method2" %}

```python
class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split(" ")
        # edge case
        if len(words) != len(pattern):
            return False
        
        # regular case
        m = {}
        for i in range(len(pattern)):
            letter = pattern[i]
            word = words[i]
            
            letter_key = 'letter_{}'.format(letter)
            word_key = "word_{}".format(word)
            
            if letter_key not in m:
                m[letter_key] = i
            if word_key not in m:
                m[word_key] = i
                
            if m[letter_key] != m[word_key]:
                return False

            
        return True
```

{% endtab %}
{% endtabs %}
