Python Solution with Dictionary


  • 1
    C

    class Solution(object):

    def wordPattern(self, pattern, str):
        d = dict()
        words = str.split(" ")
        
        l1 = len(pattern)
        l2 = len(words)
        
        if l1!=l2:
            return False
        
        for p in xrange(l1):#iterate through items in words and pattern
            
            if pattern[p] in d.keys(): #check if the pattern exists and the word match the value
                
                if d[pattern[p]]!=words[p]:
    
                    return False
            else:
                
                if words[p] in d.values(): #if the pattern not exists, but the value exists return False
                    return False
                    
            d[pattern[p]] = words[p] #if both the pattern and value not exist, add to dictionary
        
        return True

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.