2
\$\begingroup\$

I write my Python program below for this Leetcode problem:

Given a string s, find the length of the longest substring without repeating characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == "":
            return 0
        L = 1
        tmp0 = [(i,i+1) for i in range(len(s)-1)]
        # print(tmp0)
        # print(10*'-.')
        while L<=len(set(s)):
            tmp = []
            for x in tmp0:
                i, j = x
                if j < len(s) and s[j] not in s[i:j]:
                    tmp.append((i,j+1))
                    # print(tmp)
                    # print(s[i:j+1])
            if not tmp:
                break
            else:
                tmp0 = tmp
                L += 1
        return L

It passes all the tests but it runs slow. I am aware there are other faster solutions. But I would appreciate a code review for the one above. I would like to know if my idea is intrinsically slow or if it is still possible to make the code faster using the same idea. I am guessing s[j] not in s[i:j] is an expensive piece in the code.

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.