Word Pattern

Problem: Word Pattern

In this problem, we can use letter in pattern as keys in hash table and corresponding words as values. Note that we need to check whether current word has a corresponding key while scanning the word list so that we can avoid situation that several keys refer to same value, which is apparently not allowed in the problem.

Code in Python:

class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        strings = str.split(" ")
        if len(strings) != len(pattern): return False
        dict = {}
        for i in xrange(len(pattern)):
            if pattern[i] not in dict:
                for key in dict:
                    if dict[key] == strings[i]: return False
                dict[pattern[i]] = strings[i]
            elif dict[pattern[i]] != strings[i]:
                return False
        return True

results matching ""

    No results matching ""