python implementation


  • 0
    X
    class Solution(object):
        def wordPattern(self, pattern, str):
            """
            :type pattern: str
            :type str: str
            :rtype: bool
            """
            l =len(pattern)
            c = 0
            p = []
            for k in range(l):
                p.append(pattern[k])
            s = str.split()
            
            if len(s) == len(p) and l != 1:
                for i in range(l-1):
                    for j in range(i+1,l):
                        if p[i] == p[j]:
                            if s[i] == s[j]:
                                c += 1
                                continue
                            else:
                                return False
                                break
                        else:
                            if s[i] != s[j]:
                                c += 1
                                continue
                            else:
                                return False
                                break
                    if c == (l-1)*l/2:
                        return True
            if len(s) != len(p):
                return False
            if len(s) == len(p) == 1:
                return True
    

Log in to reply
 

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