Skip to content

Commit

Permalink
Word pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
LouisGobert committed Jan 17, 2024
1 parent e0a27c2 commit f411e57
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Leetcode/python/String/290. Word Pattern.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit f411e57

Please sign in to comment.