美文网首页
[Med Bi-ptr模板] 3. Longest Substr

[Med Bi-ptr模板] 3. Longest Substr

作者: Mree111 | 来源:发表于2019-10-21 08:50 被阅读0次

Description

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

Solution

使用双指针做
T O(N)
s O(MIN(M,N)) M为char set个数
1同向双指针模板

class Solution:
    """
    @param s: a string
    @return: an integer
    """
    def lengthOfLongestSubstring(self, s):
        char_set = set()
        end = 0
        max_cnt=0
        for i in range(len(s)):
            while end < len(s) and s[end] not in char_set:
                char_set.add(s[end])
                end +=1
            max_cnt = max(max_cnt,end-i)
            char_set.remove(s[i])
        return max_cnt
  1. 用dict存<char : pos>,有重复则update dict
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s)==0:
            return 0
        cdict={}
        start =0
        end = 0
        s = list(s)
        max_cnt = 0
        while end < len(s):
            if s[end] not in cdict:
                cdict[s[end]]=end
                end +=1
            else:
                if max_cnt < len(cdict):
                    max_cnt = len(cdict)
                start = cdict[s[end]]+1
                for k,v in cdict.items():
                    if v < start:
                        del cdict[k]
                
        max_cnt = max(len(cdict),max_cnt)
        return max_cnt     
           ```

相关文章

网友评论

      本文标题:[Med Bi-ptr模板] 3. Longest Substr

      本文链接:https://www.haomeiwen.com/subject/cgtzmctx.html