1 Star 0 Fork 0

libow-python / python_leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
lengthoflongestsubstring.py 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
libow-python 提交于 2021-12-14 17:14 . !4findMedianSortedArrays
def lengthOfLongestSubstring(s) -> int:
pass
# if len(s) == 1:
# return 1
# res_lst = []
# for i in range(len(s)):
# now_str = s[i]
# for j in range(i+1,len(s)):
# if s[j] not in now_str:
# now_str = now_str + s[j]
# else:
# break
# res_lst.append(now_str)
# print(res_lst)
# max = 0
# if res_lst:
# for i in res_lst:
# if len(i)> max:
# max = len(i)
# return max
"""
大体思想:找一个空的字典,记录下每一个字母的位置,如果下一次出现改字母就截取中间这一段,可以确保一定是无重复,滑动窗口
"""
st = {} # st 记录着上一次相同字母的位置
i, ans = 0, 0 # i 其实是作为一个记录上一次重复的位置
for j in range(len(s)):
if s[j] in st:
i = max(st[s[j]], i)
ans = max(ans, j - i + 1)
st[s[j]] = j + 1 # 这里的加一是为了确保字符串只有一个的时候, 返回0
return ans
if __name__ == '__main__':
print(lengthOfLongestSubstring("abbcdabcbb"))
# print(lengthOfLongestSubstring(" "))
1
https://gitee.com/libow-python/python_leetcode.git
git@gitee.com:libow-python/python_leetcode.git
libow-python
python_leetcode
python_leetcode
master

搜索帮助