Why my python code run time error?


  • 0
    A
    class Solution(object):
    def wordPattern(self, pattern, str):
        """
        :type pattern: str
        :type str: str
        :rtype: bool
        """
        p = str.split(" ")
        for i in range(len(str)):
            for j in range(i,len(pattern)):
                if p[i]==p[j]:
                    if pattern[i] <> pattern[j]:
                        return False
        
        return True

  • 0
    G

    You will get runtime error due to indexing. It is possible that the length of pattern and p to be different. You should put a restriction in the beginning with something like:

    if len(pattern) != len(p):
        return False
    

Log in to reply
 

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