题目
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.
分析
题目的输入为:一个字符串 s s
题目输出为:字符串中不包含重复字符的最长子串的长度
该题目需要注意两点,一是原字符串的子串,二是子串内不包含重复元素。对于条件一的判断,我们可以对字符串从左向右扫描,保证子串中的字符是连续的,避免出现"pwwkew"
中的情况;而为了判断是否存在重复字符,需要再加入新的字符时对其进行判断。
暴力解法是枚举出所有可能的子串,然后取长度最大的子串,但该做法的复杂度为,下面的解答则使用效率更高的方法。
解答
我们可以使用滑动窗口的方式记录最长的子串 sub s u b 。初始假设 j=i=0 j = i = 0 ,此时的窗口内的子串为 [i,j) [ i , j ) ,我们逐渐增加 j j ,当不在 sub s u b 中时,则将其添加到 sub s u b 中;反之,则找出 s[j] s [ j ] 在 sub s u b 中的位置 idx i d x ,令 i=idx+1 i = i d x + 1 ,从而保证新的 [i,j) [ i , j ) 子串中不存在重复字符。
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
substring_list = []
temp = ''
for i in s:
if i not in temp:
temp += i
else:
substring_list.append(temp)
idx = temp.index(i)
temp = temp[idx+1:] + i
substring_list.append(temp)
max_substring_len = max([len(i) for i in substring_list])
return max_substring_len
上述程序没有使用字典来记录字符的位置,而是直接利用了python中字符串内置函数index()
,从而减少了复杂的程序编写。除此之外,程序首先将所有的子串(不包含重复字符)储存在substring_list
中,然后找出最长子串的长度,从而便于程序的调试。