LeetCode 3. Longest Substring Without Repeating Characters
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.
题目解析:
class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ longest = [] length_max = 0 n = 0 for x in s: if x in longest: ix = longest.index(x) longest = longest[(ix+1):] # 舍弃前面的 longest.append(x) n = len(longest) # print(n,longest) else: longest.append(x) n += 1 # print(n, longest) if n > length_max: length_max = n return length_max滑动窗思想,从前向后扫描,遇到重复的字符,将前面的舍弃掉,并重置n,此时不可能使n增长;无重复的则添加增长字符串。慢慢领会这一思想。