Day 3 以下题目直接来源于LeetCode
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.
思路:
本题有两个比较关键的想法,一个是滑动窗口的概念,一个是巧妙利用数组编号来快速实现查找的概念,有点类似于radix sort。
滑动窗口的意思就是通过两个变量来记录下标,这两个下标中间的字符都是满足条件的,如下所示:
a b c a b c b b a b c a b c b b a b c a b c b b a b c a b c b b ...
i j i j i j i j
在这个过程中,只要滑动窗口内没有重复的字符,则通过下标i-j来求出目前满足条件字串的长度,并与之前最长的比较,更新字串。
radix sort中有一个小trick就是利用数组的标号实现编号后的符号的O(1)时间查找
比如我将‘a’编号为1,‘b’编号为2
那么若有字符串aba,在建立了一个数组count如下:
0 1 2
* * *
则出现a,就在count[1] ++,则下次滑动窗口再次检测到a,已知count[1]为1,那么就将滑动窗口的小的下标加一。
python代码(下面的只用了第一个点,radix sort的那个没有用,更优化的方法就是两个都用):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max = 1
if len(s) == 0:
return 0
elif len(s) == 1:
return 1
else:
length = len(s)
p1 = 0
p2 = p1 + 1
while p2 < length:
substr = s[p1: p2]
cur = s[p2]
if cur not in substr:
substr += cur
p2 += 1
if (p2 - p1) > max:
max = p2 - p1
else:
p1 += 1
return max