3 Longest Substring Without Repeating Characters

Method 1: Brute force try every point as start and end, 判断中间的有没有重复元素, 循环 start 和 end 的位置。时间复杂度:O(n^3)

Method 2: Sliding windows. Keep the begin pointer and the end pointer to indicate the start position and the end position. Using hash table to store information.

注意事项:previousPosition >= start 才需要变动start的位置。

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == '':
            return 0
        ans = 1 
        for i in range(len(s)):
            subs = s[i]
            for j in range(i+1,len(s)):
                if s[j] not in subs:
                    subs += s[j]
                else:
                    break
            if len(subs)>ans:
                ans = len(subs)
        return ansCopy
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if s == "":
            return 0
        length = len(s)
        start =  0
        ans = 1
        hash =  {}
        for end in range(len(s)):
            ch = s[end]
            if ch not in hash:
                if end - start + 1 > ans:
                    ans = end - start + 1
            else:
                previousPosition = hash[ch]
                if previousPosition >= start:
                    start = previousPosition + 1
                if end - start + 1 > ans:
                    ans = end - start + 1
            hash[ch] = end
        return ans

results matching ""

    No results matching ""