Skip to content

Instantly share code, notes, and snippets.

@Irene-123
Created August 13, 2020 02:45
Show Gist options
  • Save Irene-123/64358bb76a9de7ed9db7571e78d07ac6 to your computer and use it in GitHub Desktop.
Save Irene-123/64358bb76a9de7ed9db7571e78d07ac6 to your computer and use it in GitHub Desktop.
Word Pattern-LeetCode Python Solution
#Method1 :
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
map_words={}
map_chars={}
words=str.split(' ')
if len(words)!=len(pattern):
return False
for c,w in zip(pattern,words):
if c not in map_chars:
if w in map_words:
return False
else :
map_chars[c]=w
map_words[w]=c
else :
if map_chars[c]!=w:
return False
return True
#Method 2:
class Solution:
def wordPattern(self, pattern: str, str: str) -> bool:
x=str.split(' ')
len_char= len(set(pattern))
len_words=len(set(x))
return len_char==len_words and len(x)==len(pattern) and len_char==len(set(zip(pattern,x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment