Python solution with 2 hashtable

  • 0
    def wordPattern(self, pattern, str):
        words = str.split(' ')
        size = len(pattern)
        if len(words) != size:
            return False
        hash1 = {}
        hash2 = {}
        for i in xrange(size):
            if pattern[i] not in hash1:
                if words[i] in hash2:
                    return False
                hash1[pattern[i]] = words[i]
                hash2[words[i]] = pattern[i]
                if hash1[pattern[i]] != words[i]:
                    return False
        return True

Log in to reply

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