TLE but no idea what's wrong here

  • 1

    Why I always get TLE. While doing test locally, this piece of code can run fast than some code I copy from other people's answers.

    class Solution:
        # @param start, a string
        # @param end, a string
        # @param dict, a set of string
        # @return an integer
        def ladderLength(self, start, end, dict):
            if start == end:
                return 1
            visited = set()
            to_visit = [start, None]
            dis = 2
            while len(to_visit) > 1:
                word = to_visit.pop(0)
                if not word:
                    dis += 1
                if self.comp(word, end):
                    return dis
                for ele in dict:
                    if ele not in visited:
                        if self.comp(ele, word):
            return 0
        def comp(self, s, e):
            length = len(s)
            num = 0
            for i in xrange(length):
                if s[i] != e[i]:
                    num += 1
                if num > 1:
                    return False
            if not num:
                return False
            return True

Log in to reply

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