Python solution with two maps


  • 0
    def wordPattern(self, pattern, str):
            """
            :type pattern: str
            :type str: str
            :rtype: bool
            """
            forward = {}
            backward = {}
            words = str.split(' ')
            i, I = 0, len(pattern)
            j, J = 0, len(words)
            while i < I and j < J:
                if pattern[i] not in forward:
                    if words[j] in backward:
                        # its already been keyed
                        return False
                    forward[pattern[i]] = words[j]
                    backward[words[j]] = pattern[i]
                else:
                    if forward[pattern[i]] != words[j]:
                        return False
                i += 1
                j += 1
            # make sure we've consumed the pattern
            return i == I == J
    

Log in to reply
 

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