From 9dc339bf77a4bff03ea070d75823c2b1e955a1d5 Mon Sep 17 00:00:00 2001 From: Pavel Karateev Date: Mon, 2 Sep 2024 22:44:41 +0200 Subject: [PATCH] Solve "290. Word Pattern" --- .plan | 4 ++++ src/word_pattern.py | 20 ++++++++++++++++++++ tests/test_word_pattern.py | 16 ++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 src/word_pattern.py create mode 100644 tests/test_word_pattern.py diff --git a/.plan b/.plan index 513d90c..a0dd9b6 100644 --- a/.plan +++ b/.plan @@ -1,3 +1,7 @@ +Sep 2, 2024 + +* solve "290. Word Pattern" + Sep 1, 2024 complete top interview 150 diff --git a/src/word_pattern.py b/src/word_pattern.py new file mode 100644 index 0000000..178e3f7 --- /dev/null +++ b/src/word_pattern.py @@ -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 diff --git a/tests/test_word_pattern.py b/tests/test_word_pattern.py new file mode 100644 index 0000000..6a23de6 --- /dev/null +++ b/tests/test_word_pattern.py @@ -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)