找出不含重复字符的最长子串的长度

题目

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

分析

任意2个重复的字符不可能同时存在于一个合法的子串中。所以,能够从左到右扫描字符,用一个字典记录出现过的字符。
一旦发现出现过的字符,则切分为不一样的子串。
跟踪子串的最大长度便可。utf-8

时间复杂度为 O(n)string

代码

# coding: utf-8
class Solution:
  def lengthOfLongestSubstring(self, s):
    maxL = 0
    L = 0
    D = {}

    # 从第一个字符开始扫描一遍,同时记录子串长度。若是遇到字符在现有子串里已存在的,则马上终止当前子串,开始一个新子串的计数
    for c in s:
        if c not in D:
            D[c] = 1
            L += 1
        else:
            if L > maxL:
                maxL = L
            D = { c: 1 }
            L = 1
    if L > maxL:
        maxL = L
    
    return maxL


print Solution().lengthOfLongestSubstring('abrkaabcdefghijjxxx')
# 10
相关文章
相关标签/搜索