Skip to content

Commit

Permalink
Solve "290. Word Pattern"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Sep 2, 2024
1 parent bbac8cf commit 9dc339b
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .plan
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
Sep 2, 2024

* solve "290. Word Pattern"

Sep 1, 2024

complete top interview 150
Expand Down
20 changes: 20 additions & 0 deletions src/word_pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution:
def wordPattern(self, pattern: str, s: str) -> bool:
words = s.split()

if len(pattern) != len(words):
return False

letter_to_word: dict[str, str] = {}
word_to_letter: dict[str, str] = {}

for letter, word in zip(pattern, s.split()):
if letter_to_word.get(letter, word) != word:
return False
if word_to_letter.get(word, letter) != letter:
return False

letter_to_word[letter] = word
word_to_letter[word] = letter

return True
16 changes: 16 additions & 0 deletions tests/test_word_pattern.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import pytest

from src.word_pattern import Solution


@pytest.mark.parametrize(
"expected,pattern,s",
(
(True, "abba", "dog cat cat dog"),
(False, "abba", "dog cat cat fish"),
(False, "aaaa", "dog cat cat dog"),
(False, "aaa", "aa aa aa aa"),
),
)
def test_solution(expected, pattern, s):
assert expected is Solution().wordPattern(pattern, s)

0 comments on commit 9dc339b

Please sign in to comment.