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.
刚开始看到这个题时就想到设置两个变量,一个叫len记录历史最大长度,一个叫index指向当前比较子串的第一个位置。遍历字符串过程中会出现三种情况,第一个是当前字符是新字符串的首字符,第二个是当前字符可以无重复放入子串中,第三个是当前字符串在当前子串中出现重复,当前子串最大长确定,可以探索下一个子串。
当时没想清楚的问题:
- 第一种情况和第二种情况的本质是一样的,操作都是当前子串长度+1
- 忘记如何记录当前子串长度,其实i-index+1可以直接算出。每次与历史最大长度len对比即可。
- 如何判断是否出现重复,之前想着从index位置开始再遍历一下字符串,挨个对比和当前字符是否冲突,但是觉得出现双重循环很麻烦。答案里的usedchar记录了字符串s里每个字符出现的最近位置,可以用于对比是否发生重复,是个很好的思路。
- 每次发现重复时,index的位置放在哪里。一开始想着有两种可能,一是放在当前字符后,二是放在上个重复字符后。这是很多人都会犯的错误,如果放在当前字符后,那么新计算的子串长度就会忽略两个重复字符之间的不同字符。所以应该选择后者。
看完别人的答案后我写出了以下代码:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
len = 0
index = 0
usedchar = {}
for i,item in enumerate(s):
if item in usedchar and index <= usedchar[item]:
index = usedchar[item] + 1
else:
len = max(len, i - index +1)
usedchar[item] = i
return len
如果用例是”abcabcbb”的话,每次usedchar更新情况如下:
{u’a’: 0}
{u’a’: 0, u’b’: 1}
{u’a’: 0, u’c’: 2, u’b’: 1}
{u’a’: 3, u’c’: 2, u’b’: 1}
{u’a’: 3, u’c’: 2, u’b’: 4}
{u’a’: 3, u’c’: 5, u’b’: 4}
{u’a’: 3, u’c’: 5, u’b’: 6}
{u’a’: 3, u’c’: 5, u’b’: 7}
这说明usedchar记录了不同字符出现的最新位置。每次通过if item in usedchar and index <= usedchar[item]
来判断当前字符是否已经出现在当前子串中。
这道题又让我了解了一下字典的新用法。以及字典新插入元素和更新元素等操作。