290.Word Pattern
===
###### tags: `Easy`,`Hash Table`,`String`
[290. Word Pattern](https://leetcode.com/problems/word-pattern/)
### 題目描述
Given a `pattern` and a string `s`, find if `s` 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 `s`.
### 範例
**Example 1:**
```
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
```
**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` <= 300
* `pattern` contains only lower-case English letters.
* 1 <= `s.length` <= 3000
* `s` contains only lowercase English letters and spaces `' '`.
* `s` **does not contain** any leading or trailing spaces.
* All the words in s are separated by a **single space**.
### 解答
#### Python
```python=
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()
return len(set(pattern)) == len(set(words)) == len(set(zip_longest(pattern, words)))
```
> [name=Yen-Chi Chen][time=Sun, Jan 1, 2023]
#### Javascript
```javascript=
function wordPattern(pattern, s) {
const words = s.split(' ');
const map = new Map();
if (words.length !== pattern.length) return false;
for (let i = 0; i < pattern.length; i++) {
if (map.has(pattern[i])) {
if (map.get(pattern[i]) !== words[i]) return false;
} else {
if ([...map.values()].includes(words[i])) return false;
map.set(pattern[i], words[i]);
}
}
return true;
}
```
> 看到樓上的一行超人,羞愧得差點不敢發...
> [name=Marsgoat][time=Sun, Jan 1, 2023]
#### Python
```python=
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
return len(set(pattern)) == len(set(words:=s.split())) == len(set(zip_longest(pattern, words)))
```
> 這才是一行好嗎= =
> [name=Yen-Chi Chen][time=Mon, Jan 1, 2023]
### Reference
[回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)