题目
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:
Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:
Input: “pwwkew”
Output: 3
Explanation: 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
题意: 给出一个字符串,找出字符串中不含相同字符的字串,返回最大字串的长度。注意,对于空字符串返回值为0。
思路: 对字符串进行遍历,对已经遍历了的字符存放在字典中,对未遍历的字符进行判断是否在字典中出现,如果出现则更新子串的起点,最终时间复杂度为O(n)O(n)O(n)。
代码仅供参考:
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxlen = 0
left = 0 #子串起点
ss = {}
for i, ch in enumerate(s):
if ch in ss and ss[ch] >= left:
left = ss[ch] + 1
ss[ch] = i
maxlen = max(maxlen, i-left+1)
return maxlen