Python Code in 36 ms!!


  • 0
    M
    class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        output = str[:]
        output = output.split()
    
        if len(output) != len(pattern):
            return False
        else:
            unique_pattern = set(pattern)
            unique_str = set(output)
            if len(unique_str) != len(unique_pattern):
                return False
            else:
                flag = [0]*len(output)
    
                for i in range(len(pattern)):
                    if flag[i] == 0:
                        goal = output[i]
                        output[i] = pattern[i]
                        flag[i] = 1
                        for j in range(i, len(pattern)):
                            if output[j] == goal:
                                output[j] = pattern[i]
                                flag[j] = 1
    
                output = ''.join(output)
                if output == pattern:
                    return True
                else:
                    return False

  • 4
    S

    here is a 44ms one:

    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        d = {}
        s = str.split()
        if len(s) != len(pattern):
            return False
            
        for i, n in enumerate(pattern):
            if n not in d:
                d[n] = s[i]
            elif d[n] != s[i]:
                return False
        return len(d) == len(set(d.values()))

Log in to reply
 

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