超时代码:
- class Solution:
- def f(self,str):
- for i in str:
- if str.count(i)!=1:
- return False
- return True
- def lengthOfLongestSubstring(self, s: str) -> int:
- res=0
- for i in range(len(s)):
- for l in range(i,len(s)):
- if self.f(s[i:l+1]):
- res=max(res,len(s[i:l+1]))
- return res
优化思路:set取代count函数
- def f(self,str):
- set1=set()
- for i in str:
- if i in set1:
- return False
- else:
- set1.add(i)
- return True
结果:仍然超时
好吧,这是道滑动窗口的题
- class Solution:
- def lengthOfLongestSubstring(self, s: str) -> int:
- l=0
- res=0
- dic={}
- for r in range(len(s)):
- if s[r] in dic:
- l=max(l,dic[s[r]]+1)
- dic[s[r]]=r
- res=max(res,r-l+1)
- return res