Skip to content

Commit 7305566

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 290 Word Pattern
1 parent fb3f069 commit 7305566

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1616
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1717
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
1818
- [205 Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/)
19+
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
1920
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
2021
- [392 Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
2122

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution:
2+
def wordPattern(self, pattern: str, s: str) -> bool:
3+
"""
4+
Given a pattern and a string s, find if s follows the same pattern.
5+
6+
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
7+
Specifically:
8+
- Each letter in pattern maps to exactly one unique word in s.
9+
- Each unique word in s maps to exactly one letter in pattern.
10+
- No two letters map to the same word, and no two words map to the same letter.
11+
"""
12+
s = s.split()
13+
if len(pattern) != len(s):
14+
return False
15+
policy, reverse_policy = {}, {}
16+
for pattern_, s_ in zip(pattern, s):
17+
if pattern_ in policy and policy[pattern_] != s_:
18+
return False
19+
if s_ in reverse_policy and reverse_policy[s_] != pattern_:
20+
return False
21+
policy[pattern_] = s_
22+
reverse_policy[s_] = pattern_
23+
return True

tests/test_290_word_pattern.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._290_word_pattern import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["pattern", "s", "expected"],
8+
argvalues=[
9+
("abba", "dog cat cat dog", True),
10+
("abba", "dog cat cat fish", False),
11+
("aaaa", "dog cat cat dog", False),
12+
],
13+
)
14+
def test_func(pattern: str, s: str, expected: bool):
15+
word_pattern = Solution().wordPattern(pattern, s)
16+
assert word_pattern == expected

0 commit comments

Comments
 (0)