> For the complete documentation index, see [llms.txt](https://hao-fu-1.gitbook.io/oj/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://hao-fu-1.gitbook.io/oj/hash/jian-guo/word-pattern.md).

# Word Pattern

<https://leetcode.com/problems/word-pattern/description/>

> Given a`pattern`and a string`str`, find if`str`follows the same pattern.
>
> Here**follow**means a full match, such that there is a bijection between a letter in`pattern`and a**non-empty**word in`str`.
>
> **Notes:**\
> You may assume`pattern`contains only lowercase letters, and`str`contains lowercase letters separated by a single space

## Thoughts

和Isomorphic str一个套路。

## Code

```
class Solution {
    public boolean wordPattern(String pattern, String str) {
        Map<Character, String> map = new HashMap<>();
        String[] words = str.split(" ");
        if (words.length != pattern.length()) {
            return false;
        }
        for (int i = 0; i < words.length; i++) {
            if (map.containsKey(pattern.charAt(i)) && !words[i].equals(map.get(pattern.charAt(i)))) {
                return false;
            } else if (!map.containsKey(pattern.charAt(i)) && map.containsValue(words[i])) {
                return false;
            }
            map.put(pattern.charAt(i), words[i]);
        }
        return true;
    }
}
```

## Analysis

时间和空间复杂度都是O(n).
