- 【leetcode】3. 无重复字符的最长子串
- Leetcode 3: Longest Substring Wi
- LeetCode 3: Longest Substring Wi
- leetcode #3 Longest Substring Wi
- LeetCode 3 [Longest Substring Wi
- LeetCode【3】.Longest Substring Wi
- LeetCode #3 Longest Substring Wi
- leetcode(3):Longest Substring Wi
- LeetCode #3 Longest Substring Wi
- leetcode第3题 最长无重复子字符串
求解最长不重复子串 Python 3 实现:
源代码已上传 Github,持续更新。
"""
3. Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", 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.
"""
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
max_len = 0
left = 0
right = 0
dic = {}
sub_len = 0
while right < len(s):
right_value = s[right]
if right_value in dic and dic[right_value] >= left:
sub_len = right - left
max_len = max(max_len, sub_len)
left = dic[right_value] + 1
dic[right_value]=right
right += 1
else:
dic[right_value]=right
right += 1
sub_len = right - left
max_len = max(max_len, sub_len)
return max(max_len, sub_len)
if __name__ == '__main__':
solution = Solution()
print(solution.lengthOfLongestSubstring('abcabcbb'))
源代码已上传至 Github,持续更新中。
网友评论