From f411e575fe96bf300177a6296eabc82bc347d09f Mon Sep 17 00:00:00 2001 From: LouisGobert Date: Tue, 16 Jan 2024 19:39:34 -0500 Subject: [PATCH] Word pattern --- Leetcode/python/String/290. Word Pattern.py | 28 +++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Leetcode/python/String/290. Word Pattern.py diff --git a/Leetcode/python/String/290. Word Pattern.py b/Leetcode/python/String/290. Word Pattern.py new file mode 100644 index 00000000..24548cc5 --- /dev/null +++ b/Leetcode/python/String/290. Word Pattern.py @@ -0,0 +1,28 @@ +class Solution: + def wordPattern(self, pattern: str, s: str) -> bool: + char_to_word: dict[str, str] = {} + + words = s.split() + word_used = set() + if len(words) != len(pattern): + return False + for index, word in enumerate(words): + char_pattern = pattern[index] + if char_pattern in char_to_word: + if char_to_word[char_pattern] != word: + return False + + else: + if word in word_used: + return False + char_to_word[char_pattern] = word + word_used.add(word) + return True + + +if __name__ == "__main__": + s = Solution() + assert s.wordPattern(pattern="abba", s="dog cat cat dog") == True + assert s.wordPattern(pattern="aaaa", s="dog cat cat dog") == False + assert s.wordPattern(pattern="abba", s="dog cat cat fish") == False + assert s.wordPattern("abba", "dog dog dog dog") == False