题目描述
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
示例1:
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例2:
输入: “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例3:
输入: “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
暴力解法
解题思路:
用两个for循环遍历字符串,用ns存储不重复的字符,count记录最大的ns长度,当遇到重复的字符,则开始新一轮的遍历。时间复杂度为O(n^2)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
count = 0
for i in range(len(s)):
ns = [s[i]]
for j in range(i+1, len(s)):
if s[j] not in ns:
ns.append(s[j])
else:
break
if len(ns) > count:
count=len(ns)
return count
优化解
解题思路
两个相同字符之间的距离就是不重复字符的长度
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
hashmap = {}
idx = 0
dis = 0
for i in range(len(s)):
if s[i] in hashmap:
idx = max(hashmap[s[i]], idx)
dis = max(dis, i-idx+1)
hashmap[s[i]] = i+1
return dis