Created
August 13, 2020 02:45
-
-
Save Irene-123/64358bb76a9de7ed9db7571e78d07ac6 to your computer and use it in GitHub Desktop.
Word Pattern-LeetCode Python Solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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