Simple Python solution

  • 0
    class Solution(object):
        def wordPattern(self, pattern, str):
            :type pattern: str
            :type str: str
            :rtype: bool
            cs = list(pattern)
            ws = str.split()
            if len(cs) != len(ws):
                return False
            c_to_w = {}
            w_to_c = {}
            for c, w in zip(cs, ws):
                if c in c_to_w and c_to_w[c] != w:
                    return False
                if w in w_to_c and w_to_c[w] != c:
                    return False
                if c not in c_to_w:
                    c_to_w[c] = w
                if w not in w_to_c:
                    w_to_c[w] = c
            return True

Log in to reply

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