#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:Given a string, find the length of the longest substring without repeating characters.
中文:找到字符串中没有重复元素的最长子串,返回长度
举例:Given "abcabcbb", the answer is "abc". 长度为3
'''
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
Dict = {} #value->index,如果出现重复键,只存储最新的
start_index = 0 #子串开始的位置
max_len = 1 #非空,长度肯定大于0
for index ,value in enumerate(s):
if Dict.has_key(value) and Dict[value] >= start_index: #出现过,并且重复处大于子串起始位置
start_index = Dict[value] + 1 #更新子串起始位置
if max_len < (index - Dict[value]): #s[index]与s[Dict[value]]相等,不重复子串长度等于二者索引相减
max_len = index - Dict[value]
else:
if max_len < (index - start_index + 1): #s[index]与s[start_index]不相等,不重复子串长度等于二者索引相减加1
max_len = index - start_index + 1
Dict[value] = index #更新
return max_len
if __name__ == "__main__":
a = Solution()
print a.lengthOfLongestSubstring('abcdefg')
print a.lengthOfLongestSubstring('abba')
print a.lengthOfLongestSubstring('bbbbbb')
print a.lengthOfLongestSubstring('pwwkew')
3 leetcode - Longest Substring Without Repeating Characters
最新推荐文章于 2025-08-08 00:00:33 发布