Given a string, find the length of the longest substring without repeating characters.python
Examples:git
Given "abcabcbb"
, the answer is "abc"
, which the length is 3.github
Given "bbbbb"
, the answer is "b"
, with the length of 1.code
Given "pwwkew"
, the answer is "wke"
, with the length of 3. Note that the answer must be a substring, "pwke"
is a subsequence and not a substring.leetcode
遍历字符串,过程当中将出现过的字符存入字典,key为字符,value为字符下标字符串
用maxLength保存遍历过程当中找到的最大不重复子串的长度get
用start保存最长子串的开始下标string
若是字符已经出如今字典中,更新start的值it
若是字符不在字典中,更新maxLength的值io
return maxLength
class Solution(object): def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ start = maxLength = 0 usedChar = {} for i in range(len(s)): if s[i] in usedChar and start <= usedChar[s[i]]: start = usedChar[s[i]] + 1 else: maxLength = max(maxLength, i - start + 1) usedChar[s[i]] = i return maxLength
本题以及其它leetcode题目代码github地址: github地址