LeetCode No.3 Longest Substring Without Repeating Characters 20170313

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

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.

题目大意:给定一个字符串,找出其中最长的没有重复的子串。

思路:我的想法是遍历整个字符串,并且用两个变量start和end标记这个子串的头和尾,一个变量len存储当前最长子串长度,首先尾部不断向右移动,每增加一个字符就把字符存到一个字典里,这个字典存着每个字符出现的次数,如果增加一个新字符后该字符出现次数大于1,说明有重复了,这时候头部就需要不断的往右移,一直移到这个字母第一次出现的位置的后一个开始,然后尾部又开始往右移,如此往复。当遇到重复的时候,就把重复之前的尾部和头部相减,与变量中存储的之前的最长子串长度取最大值继续保存在len中。需要注意的是,当头部开始向右移动的时候,它每经过一个字符,就要在字典中将该字符出现的次数减少1,因为下一次计算的时候这些字符已经不算在内了,如果不删掉的话,下次碰到相同的字符会以为该字符在子串中重复出现,实际上该字符第一次出现的位置已经在子串头部的左边,不在子串中了。

 下面是截图和代码

class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
len, start, end = 0, 0, 0
Dict = {}
for i in s:
end += 1
Dict[i] = Dict.get(i, 0) + 1
while Dict[i] > 1:
Dict[s[start]] -= 1
start += 1
len = max(len, end - start)
return len

原文地址:https://www.cnblogs.com/fangdai/p/6545081.html