Python solution with hashmap

  • 0
    #!/usr/bin/env python                                                            
    #-*- coding:utf-8 -*-                                                            
    class Solution(object):                                                          
        def wordPattern(self, pattern, str):                                         
            :type pattern: str                                                       
            :type str: str                                                           
            :rtype: bool                                                             
            words = str.split(' ')                                                   
            map = {}                                                                 
            if len(pattern) != len(words):                                           
                return False                                                         
            if len(set(pattern)) != len(set(words)):                                 
                return False                                                                             
            for i in xrange(len(pattern)):                                           
                key = pattern[i]                                                     
                word = words[i]                                                      
                print key,word,map.get(key)                                             
                if key in map and map.get(key) != word:                                 
                        return False                                                    
                    map[key] = word                                                     
            return True                                                                 
    if __name__ == '__main__':                                                       
        s = Solution()                                                               
        print s.wordPattern("abba","dog cat cat dog")                                
        print s.wordPattern("abba","dog cat cat fish")  

Log in to reply

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