Word Pattern (Leetcode 290)

Similar to Isomorphic Strings

Problem Link: https://leetcode.com/problems/word-pattern/

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        
        l=list(map(str,s.split(' ')))
        d1={}
        n=len(pattern)
        if(len(l)!=n):
            return False
        for i in range(n):
            ch=pattern[i]
            word=l[i]
            if(ch in d1):
                if(d1[ch]!=word):
                    return False
            else:
                d1[ch]=word
        
        d2={}
        for i in range(n):
            ch=pattern[i]
            word=l[i]
            if(word in d2):
                if(d2[word]!=ch):
                    return False
            else:
                d2[word]=ch
        
        return True

Last updated