Skip to content

Instantly share code, notes, and snippets.

@kuntalchandra
Created September 7, 2020 09:28
Show Gist options
  • Select an option

  • Save kuntalchandra/55e4a518cef50fe3dc3ce4c3b1f48c60 to your computer and use it in GitHub Desktop.

Select an option

Save kuntalchandra/55e4a518cef50fe3dc3ce4c3b1f48c60 to your computer and use it in GitHub Desktop.
Word Pattern
"""
Given a pattern and a string str, find if str follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
Example 1:
Input: pattern = "abba", str = "dog cat cat dog"
Output: true
Example 2:
Input:pattern = "abba", str = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", str = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", str = "dog dog dog dog"
Output: false
Notes:
You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a
single space.
"""
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
words = str.split(" ")
if len(pattern) != len(words):
return False
map_chars = {}
map_words = {}
for c, word in zip(pattern, words):
if c in map_chars:
if map_chars[c] != word:
return False
else:
if word in map_words:
return False
else:
map_chars[c] = word
map_words[word] = c
return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment